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依赖
org.springframework.cloud spring-cloud-starter-eureka-server org.springframework.boot spring-boot-starter-security
4、在microservice-discovery-eureka的application.properties文件中设置相关参数
server.port=8761#配置安全验证,用户名及密码security.basic.enabled=truesecurity.user.name=usersecurity.user.password=password#Eureka只作为Server端,所以不用向自身注册eureka.client.register-with-eureka=falseeureka.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@EnableEurekaServerpublic class EurekaApplication { public static void main( String[] args ) { SpringApplication.run(EurekaApplication.class, args); }}
6、在microservice-provider-user的pom.xml文件中引入依赖
org.springframework.cloud spring-cloud-starter-eureka org.springframework.boot spring-boot-starter-actuator
7、在microservice-provider-user的application.properties文件中进行服务注册配置
#设置应用的名称spring.application.name=microservice-provider-user #服务注册的Eureka Server地址eureka.client.serviceUrl.defaultZone=http://user:password@localhost:8761/eureka#设置注册ipeureka.instance.prefer-ip-address=true #自定义应用实例ideureka.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