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