微服务Feign的使用
一、导入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
二、编写feign接口
加@FeignClient注解
例:
package com.lyh.mall.order.feign;
import com.lyh.common.utils.R;
import com.lyh.mall.order.vo.WareSkuLockVo;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
@FeignClient("mall-ware")
public interface WmsFeignService {
/**
* 查询sku是否有库存
* @return
*/
@PostMapping(value = "/ware/waresku/hasStock") //调用mall-ware模块接口
R getSkuHasStock(@RequestBody List<Long> skuIds);
/**
* 查询运费和收货地址信息
* @param addrId
* @return
*/
@GetMapping(value = "/ware/wareinfo/fare")
R getFare(@RequestParam("addrId") Long addrId);
}
三、在启动类上加注解
@EnableFeignClients
四、feign拦截器功能配置(带上Cookie信息)
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
/**
* @Description: feign拦截器功能
**/
@Configuration
public class FeignConfig {
@Bean("requestInterceptor")
public RequestInterceptor requestInterceptor() {
RequestInterceptor requestInterceptor = new RequestInterceptor() {
@Override
public void apply(RequestTemplate template) {
//1、使用RequestContextHolder拿到刚进来的请求数据
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (requestAttributes != null) {
//老请求
HttpServletRequest request = requestAttributes.getRequest();
if (request != null) {
//2、同步请求头的数据(主要是cookie)
//把老请求的cookie值放到新请求上来,进行一个同步
String cookie = request.getHeader("Cookie");
template.header("Cookie", cookie);
}
}
}
};
return requestInterceptor;
}
}