版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yuzhiqiang_1/article/details/84581627
一、Feign简介
Feign是一个声明式的伪Http客户端,它使得写Http客户端变得更简单。使用Feign,只需要创建一个接口并注解。它具有可插拔的注解特性,可使用Feign 注解和JAX-RS注解。Feign支持可插拔的编码器和解码器。Feign默认集成了Ribbon,并和Eureka结合,默认实现了负载均衡的效果。
简而言之:
- Feign 采用的是基于接口的注解
- Feign 整合了ribbon
二、准备工作
继续用上一节的工程, 启动discSystem-3,端口为12345; 启动discSystem-4、discSystem-4-1 ,端口分别为12346、12347.
三、创建一个feign的服务(service-feign)
四、添加application.yml
server:
port: 12349
eureka:
client:
serviceUrl:
defaultZone: http://localhost:12345/eureka/
spring:
application:
name: service-feign
五、在启动类ServiceFeignApplication ,加上@EnableFeignClients注解开启Feign的功能
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class ServiceFeignApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceFeignApplication.class, args);
}
}
六、定义一个Feign接口类(SchedualCilentName)
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* 定义一个Feign接口类
* @author 于志强
*
* 2018年11月28日 上午11:43:20
*/
@FeignClient(value = "clientName")
public interface SchedualCilentName {
// value值必须与discSystem-4、discSystem-4-1中方法名一致
@RequestMapping(value = "/test",method = RequestMethod.GET)
String sayHiFromClientOne();
}
七、定义一个对外的Controller
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* 暴漏一个可以访问的地址
* @author 于志强
*
* 2018年11月28日 上午11:45:44
*/
@RestController
public class ClientNameController {
@Autowired
SchedualCilentName schedualCilentName;
// controller中的value值不做要求 随便写
@RequestMapping(value = "/demo",method = RequestMethod.GET)
public String sayHi(){
return schedualCilentName.sayHiFromClientOne();
}
}
八、启动服务
访问(http://localhost:12345/)
访问(http://localhost:12349/demo) 浏览器交替显示:
Hello World!!! 端口为:12346
Hello World!!! 端口为:12347