1、構建microservice-spring-cloud項目,里面引入上節的服務提供者microservice-simple-provider-user和服務消費者microservice- simple-consumer-movie項目
2、在microservice-spring-cloud創建服務注冊與發現的項目microservice-discovery-eureka,作為Eureka的服務端
3、在microservice-discovery-eureka的pom.xml文件中引入eureka-server依賴
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka-server</artifactId> </dependency>
<!-- 用戶驗證依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
4、在microservice-discovery-eureka的application.properties文件中設置相關參數
server.port=8761 #配置安全驗證,用戶名及密碼 security.basic.enabled=true security.user.name=user security.user.password=password #Eureka只作為Server端,所以不用向自身注冊 eureka.client.register-with-eureka=false eureka.client.fetch-registry=false #對Eureka服務的身份驗證 eureka.client.serviceUrl.defaultZone=http://user:password@localhost:8761/eureka
5、注冊Eureka Server
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @SpringBootApplication @EnableEurekaServer public class EurekaApplication { public static void main( String[] args ) { SpringApplication.run(EurekaApplication.class, args); } }
6、在microservice-provider-user的pom.xml文件中引入依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<!-- 監控和管理生產環境的依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
7、在microservice-provider-user的application.properties文件中進行服務注冊配置
#設置應用的名稱 spring.application.name=microservice-provider-user
#服務注冊的Eureka Server地址 eureka.client.serviceUrl.defaultZone=http://user:password@localhost:8761/eureka
#設置注冊ip eureka.instance.prefer-ip-address=true
#自定義應用實例id eureka.instance.instanceId=${spring.application.name}:${spring.application.instance_id:${server.port}} #健康檢查 eureka.client.healthcheck.enabled=true
8、在microservice-provider-user中使用Eureka Client
//Eureka客戶端
@Autowired private EurekaClient eurekaClient; //服務發現客戶端
@Autowired private DiscoveryClient discoveryClient; /** * 獲得Eureka instance的信息,傳入Application NAME * * */ @GetMapping("eureka-instance") public String serviceUrl(){ InstanceInfo instance = this.eurekaClient.getNextServerFromEureka("MICROSERVICE-PROVIDER-USER", false); return instance.getHomePageUrl(); } /** * 本地服務實例信息 * */ @GetMapping("instance-info") public ServiceInstance showInfo(){ ServiceInstance localServiceInstance = this.discoveryClient.getLocalServiceInstance(); return localServiceInstance; }
9、運行結果
10、整體代碼見https://i.cnblogs.com/Files.aspx中的文件microservice-spring-cloud