Feign默认集成了Ribbon,采用基于接口的注解,并和Eureka结合,默认实现了负载均衡的效果,这里选择它,因为我觉得它更好用,废话不多说,开始实验:
1.新建一个spring-boot工程,取名feign_test
2.pom.xml中添加eureka、fein、web的起步依赖(只列出关键配置)
org.springframework.cloud
spring-cloud-starter-eureka
org.springframework.cloud
spring-cloud-starter-feign
org.springframework.boot
spring-boot-starter-web
org.springframework.cloud
spring-cloud-dependencies
Camden.SR5
pom
import
3.在application.yml文件中配置如下:
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
server:
port: 8765
spring:
application:
name: feign_test
4.main函数添加注解:
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class FeignTestApplication {
public static void main(String[] args) {
SpringApplication.run(FeignTestApplication.class, args);
}
}
5.在服务提供者service-hi(即我的博客springcloud第二步中新建的eureka客户端)中添加接口方法如下:
@RestController
public class ServiceHiApplication {
@Value("${server.port}")
String port;
@RequestMapping("/hi")
public String home(@RequestParam String name) {
return "hi "+name+"(from port:" +port+")";
}
}
6.定义一个feign接口,通过@ FeignClient(“服务名”),来指定调用哪个服务。比如在代码中调用了service-hi服务的“/hi”接口,代码如下:
@FeignClient(value = "service-hi")
public interface IHiService {
@RequestMapping(value = "/hi",method = RequestMethod.POST)
String sayHi(@RequestParam(value = "name") String name);
}
7.在Web层的controller层,对外暴露一个”/hello”的API接口,通过上面定义的Feign客户端IHiService 来消费服务。代码如下:
@RestController
public class HiController {
@Autowired
IHiService hiService
@RequestMapping(value = "/hello",method = RequestMethod.GET)
public String sayHi(@RequestParam String name){
return hiService.sayHi(name);
}
}
8.启动程序,发现Eureka服务中多了一条注册信息:
9.多次访问http://localhost:8765/hi?name=czy,浏览器交替显示:
hi czy(from port:7071)
hi czy(from port:7072)
本文参考博客:https://blog.csdn.net/forezp/article/details/69696915