Fegin在spring cloud中,比较常见的是用来类型RPC一样的远程过程调用。
AG-Admin:http://git.oschina.net/geek_qi/ace-security
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-feignartifactId>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-eurekaartifactId>
dependency>
#注册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
// “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 getPermissionByUserId(@PathVariable("id") String userId);
}
@Controller
@RequestMapping("")
public class UserPermissionController {
@Autowired
private IUserService userService;
@RequestMapping(value = "/user/system",method = RequestMethod.GET)
@ResponseBody
public String getUserSystem(){
return userService.getSystemsByUsername("admin");
}
}
如果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)
:
@Configuration
public class FooConfiguration {
@Bean
@Scope("prototype")
public Feign.Builder feignBuilder() {
return Feign.builder();
}
}
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");
}
}
Feign可以通过Java的接口支持继承。你可以把一些公共的操作放到父接口中,然后定义子接口继承之:
public interface UserService {
@RequestMapping(method = RequestMethod.GET, value ="/users/{id}")
User getUser(@PathVariable("id") long id);
}
@RestController
public class UserResource implements UserService {
}
@FeignClient("users")
public interface UserClient extends UserService {
}