一、什么是OpenFeign
OpenFeign是Spring Cloud提供的一个声明式的伪Http客户端, 它使得调用远程服务就像调用本地服务一样简单, 只需要创建一个接口并添加一个注解即可。
Nacos很好的兼容了Feign, Feign负载均衡默认集成了 Ribbon, 所以在Nacos下使用Fegin默认就实现了负载均衡的效果。
二、OpenFeign的使用
1.导入openfeign的依赖
<!--openfeign依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2.在主启动类上开启OpenFeign注解
@EnableFeignClients//开启openfeign注解
3.创建feign的接口
package com.gsh.order.feign;
import com.gsh.util.CommonResult;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@FeignClient(value = "springcloud-product")//被调用的微服务的名称
public interface ProductFeign {
//被调用的方法
@GetMapping("/product/findById/{pid}")
public CommonResult findById(@PathVariable Integer pid);
}
4.修改controller代码
(1)注入feign接口
@Autowired
private ProductFeign productFeign;
(2)使用注入的feign调用接口中的方法
//这里直接使用productFeign调用接口中的方法,和我们原来controller调用service一样啊
CommonResult byId = productFeign.findById(pid);
JSONObject jsonObject=JSONObject.fromObject(byId.getData());
System.out.println(jsonObject);
Product product = (Product) JSONObject.toBean(jsonObject, Product.class);