springcloudfeign入门搭建以及使用

编程

1.我们这里搭建feign还是用之前搭建eureka的服务,先在order服务pom文件中添加如下依赖:

<dependency>

<groupId>org.springframework.cloud</groupId>

<artifactId>spring-cloud-starter-openfeign</artifactId>

</dependency>

然后新建ProductFeignClient接口代码如下:

@FeignClient(name = "product-service")

public interface ProductFeignClient {

@RequestMapping(value = "/product/{id}", method = RequestMethod.GET)

Product findById(@PathVariable("id") Long id);

}

@FeignClient:

    name : 服务提供者的名称

2.在order服务启动类加@EnableFeignClients  这个注解代表开启feign

接下来我们修改OrderController代码:

@RestController

@RequestMapping("/order")

public class OrderController {

@Autowired

private RestTemplate restTemplate;

@Autowired

private ProductFeignClient productFeignClient;

@RequestMapping(value = "/buy/{id}",method = RequestMethod.GET)

public Product findById(@PathVariable Long id) {

Product product = productFeignClient.findById(id);

return product;

}

}

再次启动eureka、order、product服务,访问 http://localhost:9002/order/buy/1

看到这个页面我们的feign远程调用搭建成功!!!!

 

                                                                        feign负载均衡

跟上面一样启动product服务,启动两个端口,这就不多说了,前面已经演示过,现在我们直接来看结果,访问 http://localhost:9002/order/buy/1

在刷新下页面:

feign的负载均衡和我们之前的ribbon都是用轮询的方式做的负载

                                                                        

                                                                            打印feign日志

在order服务application.yml配置文件中添加如下配置:

feign:

client:

config:

product-service: #需要调用的服务名称

loggerLevel: FULL

logging:

level:

com.taiji.order.feign.ProductFeignClient: debug

配置feign日志的输出
日志配置  NONE : 不输出日志(高)   BASIC: 适用于生产环境追踪问题
HEADERS : 在BASIC的基础上,记录请求和响应头信息   FULL : 记录所有

 

以上是 springcloudfeign入门搭建以及使用 的全部内容, 来源链接: utcz.com/z/516251.html

回到顶部