1. 创建消费者模块
生成的pom文件
注意:相对于Ribbon ,多了 spring-cloud-starter-openfeign
2. 添加 相关的pojo/service/controller
其中,service 代码如下
@Service
public class ProductService {
@Autowired
ProductClientFeign productClientFeign;
public List<Product> listProducts(){
return productClientFeign.listProdcuts();
}
}
3. 创建 使用Feign 调用其他 微服务 的连接类(注意是 interface)
Feign 客户端, 通过 注解方式 访问 访问PRODUCT-DATA-SERVICE服务的 products路径, product-data-service 既不是域名也不是ip地址,而是 数据服务在 eureka 注册中心的名称。
注意看,这里只是指定了要访问的 微服务名称,但是并没有指定端口号到底是 8001, 还是 8002.
@FeignClient(value = "PRODUCT-DATA-SERVICE")// 被调用的模块名
public interface ProductClientFeign {
@GetMapping(value = "/products") //被调用的模块的接口
public List<Product> listProdcuts();
}
4. 添加properties 属性
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
spring:
application:
name: product-consumer-feign
thymeleaf:
cache: false
prefix: classpath:/templates/
suffix: .html
encoding: UTF-8
mode: HTML5
servlet:
content-type: text/html
server:
port: 8083
5. 在启动类 里添加 相关注解
@EnableEurekaClient //启用Eureka 注册中心
@EnableDiscoveryClient //注册进注册中心
@EnableFeignClients //启用Feign
相较于 Ribbon,Feign 的启动类里多了一个注解 @EnableFeignClients
关于 @EnableEurekaClient和@EnableDiscoveryClient的区别
https://blog.youkuaiyun.com/u012734441/article/details/78256256?locationNum=1&fps=1
注意: 最新springboot可能有启动类中不添加这两注解也能注册进注册中心(亲测)
6. 添加 页面html,相关工程目录结构如下
7. 启动项目,完工
注意,先启动其他的微服务模块