为Spring的RestTemplate配置HttpClient连接池和异步任务

 
    
        
        
        
        
    

    
        
        
        
            
                
                
            
        
        
            
                
                    
                    
                
                
                    
                    
                
                
                    
                    
                
            
        

    

    

    
    
        

        
        

        
        

        
        

        
        
    

    
    
    
        
        
            
        

        
        
            
                
                
                
                
                    
                        
                            application/json;charset=UTF-8
                            
                        
                    
                
                
                    
                        
                            text/plain;charset=UTF-8
                            application/json;charset=UTF-8
                            application/xml;charset=UTF-8
                        
                    
                
                
                    
                        
                            application/x-www-form-urlencoded
                        
                    
                
            
        
    
    
    
    
// 通过代码配置RestTemplate的Http连接池
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
            connectionManager.setDefaultMaxPerRoute(1000);
            connectionManager.setMaxTotal(1000);
            this.restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(
                    HttpClientBuilder.create().setConnectionManager(connectionManager).build()
            ));
// 使用Reactor+SpringMVC可以实现异步,WebFlux中直接使用WebClient实例来异步请求
// 相当于RestTemplate、AsyncRestTemplate是SpringMVC中的【RestTemplate + Reactor可以变成和WebClient一样的效果,AsyncRestTemplate是一个轻量的异步实现】,WebClient是WebFlux中的,但是WebClient性能更好
Mono.fromCallable(() -> restTemplate.getForObject(TARGET_HOST + "/hello/" + latency, String.class))
                .subscribeOn(Schedulers.elastic());

 

 

********************************* 不积跬步无以至千里,不积小流无以成江海 *********************************

你可能感兴趣的:(Spring)