SpringCloud OpenFeign 微服务调用

kyaa111 3年前 ⋅ 1032 阅读

现有xxx-common 和 xxx-user两个微服务, 现需要在common中调用user的服务

添加依赖

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

SpringBoot启动类添加注解

@EnableFeignClients

定义接口

// 微服务模块名称
@FeignClient("xxx-user")
public interface UserControllerFeign {
    //该模块中controller的url路径
    @GetMapping("/user/test/hello")
    String hello();
}

common调用

@RestController
@RequestMapping("/rpc")
public class RpcController {

    @Autowired
    UserControllerFeign userControllerFeign;

    @GetMapping("/test")
    public WebResult<String> test(){
        return WebResult.ok(userControllerFeign.hello());
    }

}

user模块中不需要进行任何改造,只要在注册中心注册了就行

user模块controller, url与feign接口对应上就行

@RestController
@RequestMapping("/user/test")
public class UserController {

    @GetMapping("/hello")
    public String hello() {
        return "this is xxx-user";
    }
}

common 接口响应

{
    "code": 200,
    "msg": "OK",
    "data": "this is xxx-user"
}

feign接口也可以这样

@FeignClient("xxx-gateway")
public interface UserControllerFeign {
    @GetMapping("/user/test/hello")
    String hello();
}

通过访问网关,然后网关再去调用对应的服务,也能实现对应的微服务调用

feign接口还能这样, 调用外部接口

@FeignClient(name = "outService", url = "http://192.168.43.140:8080")
public interface OutServiceFeign {

    @PostMapping("/auth/token")
    WebResult<AuthVO> token(@RequestBody LoginVO vo);
}

若想在非springcloud项目中使用openfeign, 需要使用如下依赖

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

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-config</artifactId>
    <version>2.2.3.RELEASE</version>
</dependency>

另: 接口对接 字段下划线转驼峰

https://www.cnblogs.com/slankka/p/13746111.html

其他一样

另: 若需对接微信的sb接口需要设置解码, 微信把json内容以text/plain的形式返回...

@Bean
    public Decoder feignDecoder() {
        MappingJackson2HttpMessageConverter wxConverter = new MappingJackson2HttpMessageConverter() {
            {
                List<MediaType> mediaTypes = new ArrayList<>();
                mediaTypes.add(MediaType.TEXT_PLAIN);
                setSupportedMediaTypes(mediaTypes);
            }
        };
        ObjectFactory<HttpMessageConverters> objectFactory = () -> new HttpMessageConverters(wxConverter);
        return new SpringDecoder(objectFactory);
    }

总结: openfeign的特性

  1. 定义一个接口就能调用到对应的服务, 接口的定义类似SpringMVC
  2. 实现原理类似MyBatis
  3. 服务降级
  4. 默认实现负载均衡
  5. 调用外部链接