前面记录服务的注册发现相关笔记是采用RestTemplate+LoadBalancerClient,有一个框架封装了微服务之间的调用,就是这个玩意。服务注册前面记录过了,这里就不说了https://my.oschina.net/uwith/blog/1929697,主要说下客户端,也就是调用服务的实现。服务注册中心是使用consul实现的。
1、老规矩在客户端先添加pom引用
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
2、application.yml配置文件添加配置信息。
server: port: 8082 spring: application: name: client-test cloud: consul: host: 192.168.1.1 port: 8500 discovery: #不注册到consul register: false
3、在application启动类上添加一个注解。不添加@EnableFeignClients注解,定义的接口会注入不进去。
@EnableFeignClients @SpringBootApplication public class ClientTestApplication { public static void main(String[] args) { SpringApplication.run(ClientTestApplication.class, args); } }
4、需要建立一个接口,来生成调用对象。@RequestMapping这个注解就表示调用服务的路径,我这个路径就是http://server-test/index
package com.example.clienttest.web; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.RequestMapping; @Component //调用服务中的注册服务名称 @FeignClient("server-test") public interface FeignClientsTest { @RequestMapping(value = "index") String index(); }
5、然后测试类
package com.example.clienttest.web; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HomeController { @Autowired FeignClientsTest feignClientsTest; @RequestMapping("/index") public String index() { String result = feignClientsTest.index(); System.out.println("请求拿到的结果:" + result); return "这里是client-test"; } }
这个东西也对熔断有支持,感觉和hystrix断路器使用区别不大。
注意:springcloud使用feign会自带超时机制,默认1S,可以调整配置文件信息来进行修改超时时间,ribbon.ReadTimeout和ConnectTimeout
参考链接:
https://blog.youkuaiyun.com/xslde_com/article/details/81153498