SpringCloud 声明式REST客户端Feign

(部分内容来自于:https://springcloud.cn/,以及周立的教程:http://edu.51cto.com/course/course_id-7348.html)

Feign是一个声明式的WebService客户端。使用Feign能让编写WebService客户端更加简单,它的使用方法是定义一个接口,然后在接口上添加注解,同时也支持JAX-RS标准的注解。Feign也支持可插拔式的编码器和解码器。SpringCloud对Feign进行了封装,使其支持SpringMVC标准注解和HttpMessageConverters。Feign可以与Eureka和Ribbon组合使用以支持负载均衡。

如何使用Feign?

添加Feign的依赖

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

这里写图片描述

在入口类上添加@EnableFeignClients注解

这里写图片描述

项目的目录结构:

这里写图片描述

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>   

这里写图片描述

UserClient.java

@FeignClient("user-server")
public interface UserClient {

    @RequestMapping(value="/getByUserId/{userId}", method=RequestMethod.GET)
    public String getByUserId(@PathVariable("userId") String userId);

}

UserController.java

@RestController
public class UserController {

    @Autowired
    private UserClient userClient;

    @RequestMapping(value="/getByUserId/{userId}", method=RequestMethod.GET)
    public String getByUserId(@PathVariable("userId") String userId){
        return userClient.getByUserId(userId);
    }

}

application.properties

#\u4FEE\u6539Tomcat\u7AEF\u53E3\u53F7
server.port=8001
#服务注册中心的配置内容,指定服务注册中心的位置
eureka.client.serviceUrl.defaultZone=http://192.168.1.12:8761/eureka/

spring.application.name=user-client

StoreClient.java

@FeignClient("stores")
public interface StoreClient {
    @RequestMapping(method = RequestMethod.GET, value = "/stores")
    List<Store> getStores();

    @RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json")
    Store update(@PathVariable("storeId") Long storeId, Store store);
}

@FeignClient注解中的stores属性可以是一个任意字符串,如果与Eureka组合使用,则stores应为Eureka中的服务名,Feign用它来创建一个Ribbon负载均衡器。也可以通过url属性来指定一个地址,可以是完整的URL,也可以是一个主机名。标注了@FeignClient注解的接口,在ApplicationContext中的Bean实例名是这个接口的全限定名,同时这个Bean还有一个别名,为Bean名+FeignClient。

覆盖Feign的默认配置

SpringCloud对Feign的封装中一个核心的概念就是客户端要有一个名字。每个客户端随时可以向远程服务发起请求,并且每个服务都可以像使用@FeignClient注解一样指定一个名字。SpringCloud会将所有的@FeignClient组合在一起创建一个新的ApplicationContext,并使用FeignClinetsConfiguration对Clients进行配置。配置中包括编码器、解码器和一个feign.Contract。

SpringCloud允许你通过configuration属性完全控制Feign的配置信息,这些配置比FeignClientsConfiguration优先级要高:

  • 8
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值