在《spring cloud 微服务实战》第168页---------请求合并这一部分,findAll方法按照书上写的运行会报错:java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.wisely.entity.User
public List<User> findAll(List<Long> ids) { return restTemplate.getForObject("http://USER-SERVICE/users1?ids={1}",List.class,StringUtils.join(ids,",")); }解决方法:
public List<User> findAll(List<Long> ids) { ParameterizedTypeReference<List<User>> responseType = new ParameterizedTypeReference<List<User>>(){}; ResponseEntity<List<User>> user = restTemplate.exchange("http://USER-SERVICE/users1?ids={1}", HttpMethod.GET, null, responseType,StringUtils.join(ids,",")); return user.getBody();
为了测试请求合并,一定要注意下面这两个参数:
timerDelayInMilliseconds //时间窗延迟的时间
execution.isolation.thread.timeoutInMilliseconds //HystrixCommand执行的超时时间
时间窗默认为10毫秒,设置的太小,请求会无法合并,为了测试可以适当设置大一些,当你设置超过1秒时,相应的也要把timeoutInMilliseconds设置大一些,该值要大于等于时间窗的时间,否则会报超时异常。这里的注意事项主要是针对书上采用注解实现请求合并器为例的:
@HystrixCollapser(batchMethod = "findAll",scope = com.netflix.hystrix.HystrixCollapser.Scope.GLOBAL, collapserProperties = {@HystrixProperty(name = "timerDelayInMilliseconds",value = "1000")}) public User find(Long id) { return null; } @HystrixCommand(commandProperties = {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "2000")}) public List<User> findAll(List<Long> ids) { ParameterizedTypeReference<List<User>> responseType = new ParameterizedTypeReference<List<User>>() { }; ResponseEntity<List<User>> user = restTemplate.exchange("http://USER-SERVICE/users1?ids={1}", HttpMethod.GET, null, responseType,StringUtils.join(ids,",")); return user.getBody();前台发起请求,controller里调用的是find方法,当短时间内(例如在一个时间窗范围内)多次访问,就会触发@HystrixCollapser注解的请求合并方法,从而调用findAll方法。有时会受网络等因素影响,有可能你接连发送了5次请求,但是只有四个合并了、有一个没合并,有时5个都合并了。我测试时用jmeter批量请求,偶尔有一两个没合并到。书上是这么定义的:HystrixCollapser实现了在HystrixCommand之前放置一个合并处理器,将处于一个很短的时间窗(默认10毫秒)内对同一依赖服务的多个请求进行整合并以批量方式发起请求的功能。
不过书上没提到HystrixCollapser有一个scope属性,scope的取值为REQUEST, GLOBAL。更多内容请参考其他博客,我会附上链接
http://blog.csdn.net/zhuchuangang/article/details/74663755
https://stackoverflow.com/questions/28821715/java-lang-classcastexception-java-util-linkedhashmap-cannot-be-cast-to-com-test