java.util.LinkedHashMap cannot be cast to com.wisely.entity.User

      在《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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值