ji接上文
ribbon做请求分发负载均衡
ribbon
配置:
server.port=9999 spring.application.name=ribbon-consumer #stores.ribbon.listOfServers=localhost:8082,localhost:8081 eureka.client.service-url.defaultZone=http://localhost:8888/eureka,http://localhost:8889/eureka
启动类
@EnableDiscoveryClient @SpringBootApplication public class EurekaRibbonRibbon1Application { @Bean @LoadBalanced RestTemplate restTemplate(){ return new RestTemplate();//面向服务调用 } public static void main(String[] args) { SpringApplication.run(EurekaRibbonRibbon1Application.class, args); } }
controller
@RestController public class ConsumerController { @Autowired private RestTemplate restTemplate; @RequestMapping("/consumer") public String helloConsumer() { // ServiceInstance serviceInstance=loadBalancerClient.choose("stores"); // URI uri=URI.create(String.format("http://%s:%s",serviceInstance.getHost(),serviceInstance.getPort())); // // return uri.toString(); return restTemplate.getForEntity("http://HELLO-SERVICE:hello", String.class).getBody(); } }
访问http://localhost:9999/consumer
发现 显示本service的端口是8082or8081 说明成功 默认是轮询可以自己设置随机等其他配置