SpringCloud-笔记5-中服务间两种调用方式-Feign

2019-11-18  本文已影响0人  牵手生活

Feign说明

描述现有wechatTask-guns中已经有helloWorld服务getToken服务

helloWorld访问无需带参数

http://127.0.0.1:8089//wechatTask//study/helloWorld

返回数据格式


image.png

在SpringCloud调用方msnSns模块的pom.xml中添加依赖

        <!--应用间铜须Feign方式-->
        <!-- SpringCloud 整合 Feign -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

在调用方的启动类添加注解

@EnableFeignClients
image.png

定义一个Feign接口(访问其他服务的接口,有点类似RetrofitClient)

/**
 * 升级Spring Boot 2.1.0 Spring Cloud Greenwich.M1  版本后,在2个Feign接口类内定义相同的名字,  @FeignClient(name = 相同的名字 就会出现报错
 * https://blog.csdn.net/ankeway/article/details/83892752
 */
@FeignClient(name = "wechat-task") //name的值是Eureka注册的服务接口
public interface HelloWorldClient {
    @GetMapping("wechatTask/study/helloWorld") //访问的路径
    String helloWorld();


    @GetMapping("wechatTask/api/getToken") //访问的路径
    IJSONResult getToken(@RequestParam String username,@RequestParam String  password,@RequestParam String  type,@RequestParam String  clientType);

}

创建一个controller进行测试HelloWorldFeignClientController


/**
 * 主要用于模拟Feign的远程调用参数种使用方式,配合@FeignClient的接口
 */

@Controller
@RequestMapping()

public class HelloWorldFeignClientController {
    Logger logger = LoggerFactory.getLogger(HelloWorldFeignClientController.class);

    @Autowired
    private HelloWorldClient helloWorldClient;//这是一个定义Feign客户端的接口



    //模拟没有参数的情况
    @GetMapping("/helloworldFeignClient")
    @ResponseBody
    public String helloworldClient(){

        String response = helloWorldClient.helloWorld();
        logger.info("响应的数据response= {}",response);
        return response;
    }



    //模拟传递惨的例子
    @GetMapping("/helloworldGetTokenFeignClient")
    @ResponseBody
    //第一种情况(直接使用restTemolate,url写死
    public IJSONResult getToken(@RequestParam String username, @RequestParam String  password, @RequestParam String  type, @RequestParam String  clientType){
        //IJSONResult ijsonResult = helloWorldClient.getToken("867463020550111","aaa6a6f01e519ea0253b7e884b3ae783a","10","10");
        IJSONResult ijsonResult = helloWorldClient.getToken(username,password,type,clientType);
        logger.info("响应的数据response= {}", JSONObject.toJSONString(ijsonResult));

        return ijsonResult;
    }

}

运行测试

image.png
http://localhost:8080//helloworldFeignClient

helloworldFeignClient没参数
http://localhost:8080/helloworldGetTokenFeignClient?username=867463020550111&password=aaa6a6f01e519ea0253b7e884b3ae783a&type=10&clientType=10

helloworldGetTokenFeignClient带参数

参考文献
Spring Cloud中如何优雅的使用Feign调用接口
FeignClient注解及参数

上一篇 下一篇

猜你喜欢

热点阅读