OpenFeign是Spring Cloud提供的一个声明式的伪Http客户端, 它使得调用远程服务就像调用本地服务一样简单, 只需要创建一个接口并添加一个注解即可。
Nacos很好的兼容了Feign, Feign负载均衡默认集成了 Ribbon, 所以在Nacos下使用Fegin默认就实现了负载均衡的效果。
-
- <dependency>
- <groupId>org.springframework.cloudgroupId>
- <artifactId>spring-cloud-starter-openfeignartifactId>
- dependency>
@EnableFeignClients//开启openfeign注解
- 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);
- }
- @Autowired
- private ProductFeign productFeign;
- //这里直接使用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);