【Spring Cloud 03】Ribbon客户端负载均衡

2021-02-24 10:51:17
新建一个微服务Module,名叫`bar-svc` pom依赖 ```xml <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` application.yml ```yaml server: port: 8002 spring: application: name: bar-service eureka: instance: hostname: bar01 instance-id: ${eureka.instance.hostname}:${server.port} prefer-ip-address: true client: register-with-eureka: true fetch-registry: true service-url: defaultZone: http://your-eureka-server-ip:8761/eureka/ ``` 使用LoadBalanced增强RestTemplate,能解析服务名,并进行负载均衡 ```java package com.example; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @SpringBootApplication @RestController public class BarApplication { public static void main(String[] args) { SpringApplication.run(BarApplication.class, args); } // 对RestTemplate进行增强 @Bean @LoadBalanced public RestTemplate restTemplate() { return new RestTemplate(); } @Autowired RestTemplate restTemplate; @GetMapping("/demo") public String demo() { // 调用 FOO-SERVICE 服务的 /version, serviceId不区分大小写,不要端口号 ResponseEntity<String> res = restTemplate.getForEntity("http://FOO-SERVICE/version", String.class); return "[bar-service] foo.version: " + res.getBody(); } } ```