springcloud 实战 feign使用中遇到的相关问题

1.使用feign客户端调用其他微服务时,session没有传递成功,sessionId不一样。

/**
* @author xbchenf
* @date 2018-10-27 16:35:52
* @description 通过拦截器,将head补上,避免session丢失
*/
@Configuration
public class FeignConfiguration implements RequestInterceptor{
private final Logger logger = LoggerFactory.getLogger(FeignConfiguration.class);
@Override
public void apply(RequestTemplate template) { RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if (requestAttributes == null) {
return;
}
HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
Enumeration<String> headerNames = request.getHeaderNames();
if (headerNames != null) {
while (headerNames.hasMoreElements()) {
String name = headerNames.nextElement();
Enumeration<String> values = request.getHeaders(name);
while (values.hasMoreElements()) {
String value = values.nextElement();
logger.warn("name:"+name+";value:"+value);
template.header(name, value);
}
}
} }
}

  

2.使用feign客户端调用其他微服务时,发送POST请求时,对象信息没有传递成功。

关键在于加上注解:@RequestBody

feign客户端:

@FeignClient(name = "mpmt-user")
public interface PersonFeignClient { @GetMapping("/feign/testGet/{id}")
public ResponseEntity<JsonResult> testGet(@PathVariable(value = "id") Integer id); @PostMapping("/feign/testPost")
public ResponseEntity<JsonResult> testPost(@RequestBody Person person);
}

  

微服务服务端:mpmt-user

@RestController
@RequestMapping("/feign")
public class FeignController { private final Logger logger = Logger.getLogger(FeignController.class); @GetMapping("/testGet/{id}")
public ResponseEntity<JsonResult> testGet(@PathVariable(value = "id") Integer id,HttpServletRequest request) {
JsonResult r = new JsonResult();
try {
logger.info("sessionid:"+request.getSession().getId());
User user = (User)request.getSession().getAttribute("sessionUser");
logger.info("userId:"+user.getId());
r.setResult(user);
r.setStatus("200");
} catch (Exception e) {
r.setResult(e.getClass().getName() + ":" + e.getMessage());
r.setStatus("error");
e.printStackTrace();
}
return ResponseEntity.ok(r);
} /**
* 添加用户
* 提供给后端feign调用的接口,post请求都要使用@RequestBody ,包括feign中定义的接口
* @param person
* @return
*/
@PostMapping("/testPost")
public ResponseEntity<JsonResult> testPost(@RequestBody Person person,HttpServletRequest request) {
JsonResult r = new JsonResult();
try {
logger.info("sessionid:"+request.getSession().getId());
User user = (User)request.getSession().getAttribute("sessionUser");
logger.info("userId:"+user.getId());
r.setResult(person);
} catch (Exception e) {
r.setResult(e.getClass().getName() + ":" + e.getMessage());
r.setStatus("error"); e.printStackTrace();
}
return ResponseEntity.ok(r);
} }

3.使用feign客户端调用其他微服务时,报错超时:e=feign.RetryableException: Read timed out executing POST

ribbon.ReadTimeout=60000
ribbon.ConnectTimeout=60000
05-11 20:12