版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011342403/article/details/88086372
最近在学习SpringCloud,由于之前已经学习过Eureka和Ribbon了。所以现在直接从Feign开始学习。当然由于没有用之前的那套代码,所以代码在这里
下面就开始Feign的学习
POM引入
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
修改Ribbon项目的启动类
在ribbon项目的启动类上加入@EnableFeignClients注解,
如下
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class WebAdminFeignApplication {
public static void main(String[] args) {
SpringApplication.run(WebAdminFeignApplication.class, args);
}
}
创建Feign接口
通过 @FeignClient(“服务名”) 注解来指定调用哪个服务。代码如下:
@FeignClient(value = "hello-spring-cloud-service-admin")
public interface AdminService {
@RequestMapping(value = "hi", method = RequestMethod.GET)
public String sayHi(@RequestParam(value = "message") String message);
}
创建 Controller
@RestController
public class AdminController {
@Autowired
private AdminService adminService;
@RequestMapping(value = "hi", method = RequestMethod.GET)
public String sayHi(@RequestParam String message) {
return adminService.sayHi(message);
}
}
配置application.yml
spring:
application:
name: hello-spring-cloud-web-admin-feign
thymeleaf:
cache: false
mode: LEGACYHTML5
encoding: UTF-8
servlet:
content-type: text/html
server:
port: 8765
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
在浏览器上多次访问链接http://localhost:8765/hi?message=HelloFeign
可以看到多次请求下,在两个服务提供者的接口上都进行了调用
Feign默认集成了Ribbon,通过interface直接实现方法调用,简化了Ribbon的操作,并且实现了负载均衡。