使用feign调用restful服务

我有一个rest接口:

@RestController
public 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.feigngroupId>
            <artifactId>feign-coreartifactId>
            <version>8.18.0version>
        dependency>
        <dependency>
            <groupId>com.netflix.feigngroupId>
            <artifactId>feign-gsonartifactId>
            <version>8.18.0version>
        dependency>
        <dependency>
            <groupId>com.google.code.gsongroupId>
            <artifactId>gsonartifactId>
            <version>${gson.version}version>
        dependency>

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

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

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

你可能感兴趣的:(java,cloud,springboot)