服务提供与调用

生产者

  • 引入依赖
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
  • 配置
spring.application.name=producer
server.port=9000
eureka.client.serviceUrl.defaultZone=http://localhost:8001/eureka/
@SpringBootApplication
@EnableDiscoveryClient
public class ProducerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ProducerApplication.class, args);
    }

}

消费者

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
@EnableDiscoveryClient
@EnableFeignClients
public class ConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class, args);
    }
}

@FeignClient("producer")
public interface HelloRemote {

    @RequestMapping("/hello")
    String hello(@RequestParam String name);
}
  • 使用
@RestController
public class ConsumerController {
    @Autowired
    HelloRemote helloRemote;

    @RequestMapping("/hi")
    public String hi(){
        return helloRemote.hello("my");
    }

}
  • 请求压缩
feign:
  compression:
    request:
      enabled: true # 开启请求压缩
    response:
      enabled: true # 开启响应压缩

负载均衡

分别启动两个生产者,则两个生产者同时提供服务

  • 客户端负载均衡
    • 从注册中心服务器端上获取服务注册信息列表,缓存到本地。后在本地实现轮训负载均衡策略
  • 服务端负载均衡
    • 客户端所有请求统一交给一台服务器,由这台服务器进行实现负载均衡请求转发

本地负载均衡的实现

// 随机负载均衡
List<ServiceInstance> list = discoveryClient.getInstances("producer");
Random random = new Random();
ServiceInstance serviceInstance = list.get(random.nextInt(list.size()));
// 使用Ribbon
@RestController
public class Controller {
    @Autowired
    LoadBalancerClient client;

    @RequestMapping("/user")
    public String user(){
        return new RestTemplate().getForObject(
                client.choose("user-service").getUri().toString()+"/user",String.class);
    }
}
// 另外一种方法
@Autowired
RestTemplate restTemplate;

@RequestMapping("/user")
public String user(){
    return restTemplate.getForObject("http://user-service/user",String.class);
}

@Bean
@LoadBalanced
public RestTemplate restTemplate(){
    return new RestTemplate();
}
  • 负载均衡策略
# 修改负载均衡策略
user-service.ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.RandomRule

results matching " "

No results matching " "

results matching " "

No results matching " "