springcloud 入门(3) 声明式调用 Feign

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第9天,点击查看详情

springcloud 搭建更多请查看:
springcloud 项目一步一步搭建(1)之eureka
springcloud 项目一步一步搭建(2)之Ribbon

spring cloud feign 介绍

Spring Cloud Feign担任的角色是声明式服务调用。在之前我们只是简单使用RestTemplate,但在实际开发中,由于对服务依赖调用可能不止一处,往往一个接口会被多处调用,所以通常都会针对各个微服务自行封装一些客户端来包装这些依赖服务的调用,我们发现对于RestTemplate的封装,几乎每一个调用都是模板化内容。针对上述情况,Spring Cloud Feign在此基础上进一步封装,由它来帮助我们定义和实现依赖服务接口的定义,使得我们在调用接口时完全感觉不到是在进行远程接口调用。

Spring Cloud Feign 的使用

Spring Cloud Feign 使用起来也很简单: 生产者: ProductController.java

@RestController
@RequestMapping("/product")
public class ProductController {

    @GetMapping("/list/{count}")
    public List<ProductEntity> list(@PathVariable("count") int count){
        List<ProductEntity> list = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            ProductEntity productEntity = new ProductEntity();
            productEntity.setName("name-"+i);
            productEntity.setType("type-"+i);
            list.add(productEntity);
        }
        return list;
    }
}
复制代码

ProductEntity.java

public class ProductEntity {
    private String name;
    private String type;
    //get、set方法省略
}
复制代码

1、创建maven项目,引入Spring Cloud Feign 相关依赖

		<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>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
复制代码

2、在启动类加入@EnableFeignClients注解,在程序启动后会扫描带有@FeignClient注解的类

@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name = "PROVIDER" , configuration = RibbonConfig.class)
@EnableFeignClients
public class ConsumerFeignApplication {

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

}
复制代码

3、application.properties配置

server.port=7002

eureka.client.register-with-eureka=false

eureka.client.service-url.defaultZone=http://localhost:8001/eureka
spring.application.name=consumer
eureka.instance.instance-id=consumer-feign
复制代码

4、定义 FeignClient

@FeignClient(name = "PROVIDER")
public interface IProviderService {

    @RequestMapping("/hi/hello")
    String hi();

    @RequestMapping("/product/list/{count}")
    List<ProductEntity> productList(@PathVariable("count") int count);
}
复制代码

5、在消费者端调用FeignClient

@RestController
@RequestMapping("/hi")
public class HelloConsumerFeign {
    @Autowired
    private IProviderService iProviderService;

    @RequestMapping("/pro")
    public String provider(){
        return iProviderService.hi();
    }

    @GetMapping("/productList/{count}")
    public List<ProductEntity> productList(@PathVariable("count") int count){
        return iProviderService.productList(count);
    }
}
复制代码

启动Eureka Server 、生产者、feign消费者,访问http://localhost:7002/hi/productList/5 , 出现如下页面访问成功 在这里插入图片描述

扫描二维码关注公众号,回复: 14439242 查看本文章

FeignClient 注解剖析

1、name:FeignClient 的名称,对应生产者服务名称,用于服务发现 2、url:一般用于调试,可以指定@FeignClient 的调用地址 3、decode404:错误代码为404时,如果该字段为true,会调用decoder进行解码,否则抛出FeignException 4、configuration:配置类,可以自定义Feign的Decoder、Encoder、Contract、LogLevel等 5、fallback:定义容错的处理类,当调用远程接口失败或者超时时,会调用接口对应的容错逻辑,fallback指定的类必须实现@FeignClient 标记的接口。 6、fallbackFactory:工厂类,用于生成fallback类示例类,通过这个接口我们可以实现每个接口通用的容错逻辑,减少重复代码。

Feign 开启GZIP压缩

spring cloud feign支持请求响应的gzip压缩。

# 配置请求GZIP压缩
feign.compression.request.enabled=true
# 配置响应GZIP压缩
feign.compression.response.enabled=true
# 配置压缩支持的mime type
feign.compression.request.mime-types="text/xml", "application/xml", "application/json"
# 配置压缩数据大小的下限,默认2048
feign.compression.request.min-request-size=2048
复制代码

Feign client 开启日志

Feign 为每个Feign client 都提供了feign.Logger实例,可在配置中开启日志。 开启日志分为两步: 1、创建FeignClientConfig类配置日志bean

@Configuration
public class FeignClientConfig {
    @Bean
    public Logger.Level getFeignLoggerLevel() {
        return feign.Logger.Level.FULL;
    }
}
复制代码

2、在配置文件中配置日志

# 开启日志
logging.level.site.sunlong.eurekaConsumer.service=debug
复制代码

配置完之后就能在控制台看到日志了。

参考资料:
1、《springcloud 微服务实战》
2、《重新定义Spring Cloud 实战》

GitHub地址: github.com/ArronSun/mi…

猜你喜欢

转载自juejin.im/post/7127866478300233735