服务消费和负载(Feign)

Spring Cloud Feign

Spring Cloud Feign是一套基于Netflix Feign实现的声明式服务调用客户端。它使得编写Web服务客户端变得更加简单。我们只需要通过创建接口并用注解来配置它既可完成对Web服务接口的绑定。它具备可插拔的注解支持,包括Feign注解、JAX-RS注解。它也支持可插拔的编码器和解码器。Spring Cloud Feign还扩展了对Spring MVC注解的支持,同时还整合了Ribbon来提供均衡负载的HTTP客户端实现。

添加依赖

修改 spring-cloud-consul-consumer 的 pom 文件,添加 feign 依赖。

pom.xml

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>

修改启动器

修改启动器类,添加 @EnableFeignClients 注解开启扫描Spring Cloud Feign客户端的功能:

ConsuleConsumerApplication.java

复制代码
package com.louis.spring.cloud.consul.consumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@EnableFeignClients
@SpringBootApplication
public class ConsuleConsumerApplication {

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

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}
复制代码

添加Feign接口

添加 FeignHelloService 接口, 在类头添加注解 @FeignClient("service-producer") ,service-producer是要调用的服务名。

添加跟调用目标方法一样的方法声明,只需要方法声明,不需要具体实现,注意跟目标方法定义保持一致。

FeignHelloService.java

复制代码
package com.louis.spring.cloud.consul.consumer.service;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;

@FeignClient("service-producer")
public interface FeignHelloService {

    @RequestMapping("/hello")
    public String hello();
}
复制代码

添加控制器

添加 FeignHelloController 控制器,注入 FeignHelloService,就可以像使用本地方法一样进行调用了。

FeignHelloController.java

复制代码
package com.louis.spring.cloud.consul.consumer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.louis.spring.cloud.consul.consumer.service.FeignHelloService;

@RestController
public class FeignHelloController {

    @Autowired
    private FeignHelloService feignHelloService;
    
    @RequestMapping("/feign/call")
    public String call() {
        // 像调用本地服务一样
        return feignHelloService.hello();
    }
}
复制代码

测试效果

启动成功之后,访问 http://localhost:8521/feign/call,发现调用成功,且 hello consul 和  hello consul two 结果随机出现。

这是因为 Feign 是基于 Ribbon 实现负载均衡的,而我们在上一节中配置了 Ribbon 的负载策略为随机策略。

 

猜你喜欢

转载自www.cnblogs.com/7788IT/p/10667071.html