Spring Cloud Feign 服务消费者

Feign是一个声明式的Web Service客户端,它使得编写Web Serivce客户端变得更加简单。我们只需要使用Feign来创建一个接口并用注解来配置它既可完成。它具备可插拔的注解支持,包括Feign注解和JAX-RS注解。Feign也支持可插拔的编码器和解码器。Spring Cloud为Feign增加了对Spring MVC注解的支持,还整合了Ribbon和Eureka来提供均衡负载的HTTP客户端实现。

 导入Feign依赖

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

在应用主类中通过@EnableFeignClients注解开启Feign功能

/**
 * @author 向振华
 * @date 2018/10/23 17:00
 */
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class).web(true).run(args);
    }

}

定义SystemMessageClient引入消息服务的接口

/**
 *  消息服务
 * @author 向振华
 * @date 2018/11/28 14:42
 */
@FeignClient(value = "front-service", path = "/systemMessage", fallback = SystemMessageClientFallBack.class)
public interface SystemMessageClient {

    /**
     * 获取公告
     */
    @RequestMapping(value = "/bulletinList", method = RequestMethod.POST)
    ResponseMessage<PageBean<SystemMessageVO>> bulletinList(PageSizeReq req);
}
/**
 *  服务降级
 * @author 向振华
 * @date 2018/11/30 11:48
 */
@Component
public class CouponClientFallBack implements CouponClient {

    private static ResponseMessage fallbackRes = new ResponseMessage(-1, "服务暂不可用", null);

    @Override
    public ResponseMessage<PageBean<CouponVO>> userCouponsList(UseCouponReq useCouponReq) {
        return fallbackRes;
    }
}

@FeignClient value绑定该接口对应front-service服务, path服务访问url,fallback服务降级。

通过Spring MVC的注解来配置front-service服务下的具体实现

使用:

    @Resource
    private SystemMessageClient systemMessageClient;

    @Override
    public ResponseMessage bulletinList(PageSizeReq req) {
        ResponseMessage<PageBean<SystemMessageVO>> res = systemMessageClient.bulletinList(req);
        return buildRes(res);
    }
扫描二维码关注公众号,回复: 5070083 查看本文章

猜你喜欢

转载自blog.csdn.net/Anenan/article/details/85062666