天天看點

微服務——注冊中心

SpringCloud——Eureka

注冊中心服務端——EurekaServer

導入依賴:EurekaServer

所需配置:

server:
  port: 8761
eureka:
  instance:
    hostname: localhost     # eureka服務端的實力名稱
  client:
    fetch-registry: false  # false表示自己就是注冊中心。我的職責就是維護服務執行個體,并不需要去檢索服務
    register-with-eureka: false   # false表示自己不需要向注冊中心注冊自己
    service-url:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/      # 設定與Eureka Server互動的位址查詢服務和注冊服務都需要依賴這個位址(單機版)
#      defaultZone: http://localhost:8765/eureka/


           

代碼需要:在主類上添加注解

@SpringBootApplication
@EnableEurekaServer//需要這個注解
public class TicketRegserverApplication {

    public static void main(String[] args) {
        SpringApplication.run(TicketRegserverApplication.class, args);
    }

}
           

注冊中心用戶端——EurekaClient

需要依賴:EurekaClient

注意:手動導入時需要

1、

<properties>
		<java.version>1.8</java.version>
		<spring-cloud.version>Hoxton.SR9</spring-cloud.version><!--需要添加這個,與服務端引入依賴後的相對應-->
	</properties>
	
           

2、以下這一部分寫在後面,也是與服務端映入依賴後相對應

<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-dependencies</artifactId>
				<version>${spring-cloud.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>
           

需要配置:

spring.application.name=ticket-user  #客服端的名字
eureka:
  client.serviceUrl.defaultZone=http://localhost:8761/eureka/   #與伺服器端設定的defaultZone相對應
           

代碼需要:

@Configuration
public class TicketConfig {
    @Bean
    @LoadBalanced//RestTemplate的javaBean處需要添加這個負載均衡的注解
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}
           

使用:

注意:有一個坑,用戶端的名字不能包含下劃線