Spring cloud实战-Fegin简易使用

来源:互联网 发布:100以内质数的和c语言 编辑:程序博客网 时间:2024/06/05 08:55

Fegin、Eureka

Fegin在spring cloud中,比较常见的是用来类型RPC一样的远程过程调用。

项目地址:

AG-Admin:http://git.oschina.net/geek_qi/ace-security

简易使用

Maven依赖

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

application.yml 配置

#注册eureka服务eureka:    instance:        statusPageUrlPath: ${management.context-path}/info        healthCheckUrlPath: ${management.context-path}/health    client:        serviceUrl:            defaultZone: http://localhost:8761/eureka/#请求和响应GZIP压缩支持feign:  compression:    request:      enabled: true      mime-types: text/xml,application/xml,application/json      min-request-size: 2048    response:      enabled: true

基于Eureka的Fegin写法

// “back”为Euerka中服务注册名@FeignClient("back")public interface IUserService {  @RequestMapping(value = "/service/user/username/{username}", method = RequestMethod.GET)  public UserInfo getUserByUsername(@PathVariable("username") String username);  @RequestMapping(value = "/service/user/{id}/permissions", method = RequestMethod.GET)  public List<PermissionInfo> getPermissionByUserId(@PathVariable("id") String userId);}

Fegin Bean的调用

@Controller@RequestMapping("")public class UserPermissionController {    @Autowired    private IUserService userService;    @RequestMapping(value = "/user/system",method = RequestMethod.GET)    @ResponseBody    public String getUserSystem(){       return userService.getSystemsByUsername("admin");    }}

Feign与Hystrix

如果Hystrix在classpath中,Feign会默认将所有方法都封装到断路器中。Returning a com.netflix.hystrix.HystrixCommand is also available。这样一来你就可以使用Reactive Pattern了。(调用.toObservalbe()或.observe()方法,或者通过.queue()进行异步调用)。

feign.hystrix.enabled=false参数设为false可以关闭对Hystrix的支持。

如果想只关闭指定客户端的Hystrix支持,创建一个Feign.Builder组件并标注为@Scope(prototype)

@Configurationpublic class FooConfiguration {    @Bean    @Scope("prototype")    public Feign.Builder feignBuilder() {        return Feign.builder();    }}

Feign对Hystrix Fallback的支持

Hystrix支持fallback的概念,即当断路器打开或发生错误时执行指定的失败逻辑。要为指定的@FeignClient启用Fallback支持, 需要在fallback属性中指定实现类:

@FeignClient(name = "hello", fallback = HystrixClientFallback.class)protected interface HystrixClient {    @RequestMapping(method = RequestMethod.GET, value = "/hello")    Hello iFailSometimes();}static class HystrixClientFallback implements HystrixClient {    @Override    public Hello iFailSometimes() {        return new Hello("fallback");    }}

Fegin的继承

Feign可以通过Java的接口支持继承。你可以把一些公共的操作放到父接口中,然后定义子接口继承之:

接口

public interface UserService {    @RequestMapping(method = RequestMethod.GET, value ="/users/{id}")    User getUser(@PathVariable("id") long id);}

实现

@RestControllerpublic class UserResource implements UserService {}

客户端

@FeignClient("users")public interface UserClient extends UserService {}