Spring Cloud之feign入门


Feign

简介

Feign makes writing java http clients easier

https://github.com/OpenFeign/feign

Feign可以把Rest的请求进行隐藏,伪装成类似SpringMVC的Controller一样。你不用再自己拼接url,拼接参数等等操作,一切都交给Feign去做。


比如:

远程调用的请求我们需要这样封装

String url = "http://user-service/user/" + id;
User user = restTemplate.getForObject(url, User.class);

然而通过Feign:

可以一句话搞定(通过注解和接口及依赖自动注入隐藏实现,代码更简洁业务逻辑清晰,耦合低)

使用

引入依赖

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

配置启动类

@EnableFeignClients

@EnableFeignClients
@SpringCloudApplication
public class ConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class,args);
    }

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

编写客户端类接口(替代通过https拼接url远程调用)

package an.study.consumer.client;

import an.study.consumer.pojo.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
//        想办法替代下面两句话
//        String url = "http://user-service/user/" + id;
//        User user = restTemplate.getForObject(url, User.class);
@FeignClient("user-service")
public interface UserClient {
    @GetMapping("/user/{id}")
    User getOneUser(@PathVariable("id")Integer id);

}

使用实例

自动注入

@Autowired
private UserClient userClient;

然后调用方法

userClient.getOneUser(id);

即可

使用Feign配置ribbon和hystrix

配置文件

feign:
  hystrix:
    enabled:

ribbon:
  ConnectionTimeOut: 500
  ReadTimeOut: 2000

Feibin注解的接口

@FeignClient(value = "user-service",fallback = UserFeignClientFallback.class)
public interface UserClient {
    @GetMapping("/user/{id}")
    User getOneUser(@PathVariable("id")Integer id);

}

fallback接口

@Component注解很重要!否则会出现异常No fallback instance of type class found for feign client

@Component
public class UserFeignClientFallback implements UserClient {
    @Override
    public User getOneUser(Integer id) {
        User user = new User();
        user.setName("未知");
        return user;
    }
}

文章作者: Bxan
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Bxan !
  目录