天天看點

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

繼續閱讀