spring-cloud(5)、REST客户端 — Feign

  客户端和服务端之间的调用,前面说过了Ribbon,现在说另一种Rest类型的客户端Feign,之前的demo有些简单不涉及到参数的传递,所以本次修改服务端提供的接口增加参数来进行简单的字符串拼接,其实写法跟HTTP请求差不多。

  • 服务端

  服务端(Server Module)增加一个拼装接口,代码如下

package com.fzhsh.cloud.server;

@SpringBootApplication
@EnableEurekaClient
@RestController
public class ServerApp {

    @RequestMapping("/home")
    public String hello(){
        System.out.println("call home");
        return "test - home";
    }

    @PostMapping("/concat")
    public String concat(@RequestParam("str") String str){
        return "Hello," + str;
    }

    public static void main(String[] args) {
        SpringApplication.run(ServerApp.class, args);
    }
}

 

  • 客户端

  客户端在原有的Module(Client)上继续集成

  首先,POM增加Feign的依赖

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

  然后,在启动主类ClientApp.java上增加@EnableFeignClients

package com.fzhsh.cloud.clent;

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class ClientApp {

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

    public static void main(String[] args) {
        SpringApplication.run(ClientApp.class, args);
    }
}

  接着,编写调用接口,按照REST的格式

package com.fzhsh.cloud.clent.service;

@FeignClient("server")
public interface CallClient {

    @PostMapping("/concat")
    String concat(@RequestParam("str")String str);

}

  再接着,编写接口调用

package com.fzhsh.cloud.clent.web;

@RestController
public class IndexController {

    @Autowired
    private CallClient callClient;

    @GetMapping("/concat")
    public String concat(@RequestParam("str") String str){
        return callClient.concat(str);
    }

}

  最后,访问http://localhost:8080/concat?str=Linda,结果为

Hello,Linda
  • 参考资料

http://cloud.spring.io/spring-cloud-static/Dalston.SR1/#spring-cloud-feign

posted @ 2017-06-12 16:02  風之殤  阅读(145)  评论(0)    收藏  举报