ribbon在有eureka的情况下, 可以不使用eureka, 挺简单, 直接上代码
application.xml
server: port: 7002 spring: # 设置eureka中注册的名称, 全小写, 否则大小写混杂出现问题 application: name: microservice-consumer-movie-ribben-yml logging: level: root: INFO org.hibernate: INFO org.hibernate.type.descriptor.sql.BasicBinder: TRACE org.hibernate.type.descriptor.sql.BasicExtractor: TRACE com.itmuch: DEBUG eureka: client: serviceUrl: defaultZone: http://wenbronk:abc@localhost:8761/eureka # 添加注册中心中的ip代替主机名 instance: prefer-ip-c: true instance-id: ${spring.application.name}:${spring.cloud.client.ipAddress}:${spring.application.instance_id:${server.port}} statusPageUrlPath: ${management.context-path}/info healthCheckUrlPath: ${management.context-path}/health # 在ribbon中禁用eureka ribbon: eureka: enabled: false # 自定义ribbonclient, 不使用eureka, 使用这个配置 microservice-provider-user: ribbon: listOfServers: localhost:7901
2, MovieController中使用此方法测试:
@RequestMapping("/movie/{id}") public User findById(@PathVariable Long id) { ServiceInstance instance = this.loadBalancerClient.choose("microservice-provider-user"); URI storesUri = URI.create(String.format("http://%s:%s", instance.getHost(), instance.getPort())); System.out.println("111: " + instance.getServiceId() + ": " + instance.getHost() + ": " + instance.getPort()); return null; // return restTemplate.getForObject("http://microservice-provider-user/simple/" + id, User.class); }
客户端发起请求后 , 可看到日志里面只有 7901 端口在被访问, 注释掉yml中的最后2项配置, 就可以看到eureka默认的轮询配置