Feigh
Feign则是在Ribbon的基础上进行了一次改进,采用接口的方式,将需要调用的其他服务的方法定义成抽象方法即可,不需要自己构建http请求。不过要注意的是抽象方法的注解、方法签名要和提供服务的方法完全一致。 Feign是一个伪RPC客户端(本质还是用http);
一、依赖
<!--ribbon客户端依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>二、负载均衡随机配置
随机回去服务器的服务,而不是轮询,Feign是基于ribbon的,所以基本配置与ribbon差不多
product-service:
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule三、开启注解
@EnableFeignClients
四、接口的定义
调用其它服务的接口,需要与调用接口的服务方法一致。如果参数使用@RequestParam。 name表示的是服务名,GetMapping表示的是请求url。
@FeignClient(name = "service-name")
public interface FeignClientTest {
@GetMapping("/getProductById")
String getById(@RequestParam(value = "productId") Long productId);
}五、接口的使用
使用@Autowired注解,将对象生成,然后调用返回相应的数据。
@Autowired
private ProductOrderClient productOrderClient;
public Map<String,Object> query(Long id){
//返回的数据
String response = feignClientTest.getById(id);
//ObjectMapper对象
ObjectMapper objectMapper = new ObjectMapper();
try {
//转成jsonNode
JsonNode jsonNode = objectMapper.readTree(response);
} catch (IOException e) {
e.printStackTrace();
}
}六、feign调用携带header
正常情况下feign调用的时候不会携带接口发送者的header,这里需要手动去配置。
/**
* @Description feign调用token携带
* @Author lcy
* @Date 2021/6/9 10:31
*/
@Configuration
@Slf4j
public class TokenRequestInterceptor implements RequestInterceptor {
@Override public void apply(RequestTemplate requestTemplate){
try {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
// 获取该次请求得token 将token传递
if (requestAttributes != null) {
HttpServletRequest request = requestAttributes.getRequest();
String token = request.getHeader("token");
if (StringUtils.isNotBlank(token)) {
requestTemplate.header("token",token);
}
}
} catch (Exception e) {
log.error("获取header里的token异常。 ",e);
}
}
}