• spring cloud学习(四) Fegin 的使用


    Feign 的使用

    什么是Feign?

    Feign : Declarative REST clients。
    Feign 是一个声明web服务客户端,这便得编写web服务客户端更容易,使用Feign 创建一个接口并对它进行注解,它具有可插拔的注解支持包括Feign注解与JAX-RS注解,Feign还支持可插拔的编码器与解码器,Spring Cloud 增加了对 Spring MVC的注解,Spring Web 默认使用了HttpMessageConverters, Spring Cloud 集成 Ribbon 和 Eureka 提供的负载均衡的HTTP客户端 Feign。(来源于Spring Cloud Netflix 官网文档)

    怎么使用Feign

    首先继续使用上次的”服务注册中心”与”服务提供者”。接下来,就是将 Fegin 整合到”服务消费者”中。

    引入依赖

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

    注入注解

    在 Spring Boot 主类加入注解@EnableFeignClients开启 Fegin 功能。

    注入接口

    创建接口,具体如下:

    @Component
    @FeignClient(value = "my-service")
    public interface ServiceClient {
    
        @RequestMapping("/service")
        String printf();
    }
    
    • 使用@Component注解向 Spring Boot 中注入该组件。
    • 使用@FeignClient("")注解来绑定该接口对应的服务
    • 通过 Spring MVC 的注解来配置服务下的具体实现。

    在Controller中调用接口

    @RestController
    public class ConsumerController {
    
        @Autowired
        private ServiceClient serviceClient;
    
        @RequestMapping("/test")
        public String test(){
            return serviceClient.printf();
        }
    }
    

    最后,启动”注册中心”、”服务提供者”、”服务消费者”等工程。访问 http://localhost:2222/test 就可以在”服务提供者”控制台查看到负载均衡的实现。

    注意事项

    注意注意注意
    当Spring Cloud版本为 Brixton.RELEASE ,会抛出异常:

    Attribute ‘value’ in annotation [org.springframework.cloud.netflix.feign.FeignClient] must be declared as an @AliasFor [serviceId], not [name]
    

    解决办法:
    将Spring Cloud版本改为 Brixton.SR5 或 Camden.RELEASE 即可。

  • 相关阅读:
    (字典树)Revenge of Fibonacci -- HDU -- 4099
    (字符串 KMP)Blue Jeans -- POJ -- 3080:
    (广搜)聪明的打字员 -- POJ --1184
    (线段树 点更新 区间求和)lightoj1112
    Jquery弹窗插件Lhgdialog的用法
    SQL Server数据库大型应用解决方案总结
    C# 使用XmlDocument类对XML文档进行操作
    反射实例【转】
    如何使用dynamic
    [C#]DataTable常用操作总结
  • 原文地址:https://www.cnblogs.com/MaxElephant/p/8109201.html
Copyright © 2020-2023  润新知