使用feign调用restful服务

来源:互联网 发布:javascript跳转新页面 编辑:程序博客网 时间:2024/06/15 08:38

我有一个rest接口:

@RestControllerpublic class ComputeController {    @RequestMapping(value = "/add", method = RequestMethod.GET)    public String add() {        return "testFeign_add";    }    @RequestMapping(value = "/add2")    public Integer add2(@RequestParam Integer a, @RequestParam Integer b) {        int rs = a + b;        return rs;    }}

怎么调用呢:

public static void main(String[] args) {    ComputeService computeService = Feign.builder().decoder(new GsonDecoder()).target(ComputeService.class,                "http://localhost:3333");    System.out.println(computeService.add());    System.out.println(computeService.add2(1,2));    System.out.println(computeService.add3(1,2));}

看看ComputeService 怎么写的:

public interface ComputeService {    @RequestLine("GET /add")    public String add();    @RequestLine("GET /add2?a={a}&b={b}")// get 提交    public Integer add2(@Param("a") Integer a, @Param("b") Integer b);    @RequestLine("POST /add2")    @Body("a={a}&b={b}")// post 提交    public Integer add2(@Param("a") Integer a, @Param("b") Integer b);}

用到的依赖.

这里反序列化用的是gson,jackson的自己换一下,fastjson等目前是不支持的,自己面壁去写。restful依赖的就不贴了
        <dependency>            <groupId>com.netflix.feign</groupId>            <artifactId>feign-core</artifactId>            <version>8.18.0</version>        </dependency>        <dependency>            <groupId>com.netflix.feign</groupId>            <artifactId>feign-gson</artifactId>            <version>8.18.0</version>        </dependency>        <dependency>            <groupId>com.google.code.gson</groupId>            <artifactId>gson</artifactId>            <version>${gson.version}</version>        </dependency>

简直不要太简单。不过要求比较高的地方需要配置一下底层的httpclient,比如连接池、比如超时时间,还有更高级的服务订阅、负载均衡和断路器。

Ps:在分布式服务中通常用ribbon做负载均衡器,用hystrix做断路器,用zookeeper或者euraka做服务发布。建议用springcloud的一整套解决方案。

用f5的就不用这些了,f5有自己的负载均衡。使用f5需要考虑单点和性能问题,F5方案毕竟多走了一层网络。

0 0
原创粉丝点击