如何通过Ribbon实现负载均衡
由于Eureka依赖本身就自带Ribbon,故无需再添加依赖
@EnableEurekaClient
@SpringBootApplication
public class ScbrlWebApplication {
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(ScbrlWebApplication.class, args);
}
}
· 只需要在RestTemplate添加@LoadBalanced注解即可实现默认轮询负载
· 注:restTemplate需在ScbrlWebApplication加载时将@Bean注入Spring容器
如何使RestTemplate请求自动添加请求头
· 添加自定义请求拦截器
/**
* 模块:【RestTemplate请求拦截器】
* <p>
* 开发: Bruce.Liu By 2017/11/20 下午8:06 Create
*/
public class RestUserAgentInterceptor implements ClientHttpRequestInterceptor {
/**
* RestTemplate请求加上默认请求头(签名、时间轴)
* @param request
* @param body
* @param execution
* @return
* @throws IOException
*/
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
HttpHeaders headers = request.getHeaders();
String timestamp = System.currentTimeMillis()+"";
headers.add("timestamp",timestamp);
headers.add("sign", MD5Util.RestfulSign(timestamp,
InetAddress.getLocalHost().getHostAddress()));
return execution.execute(request, body);
}
}
· RestTemplate 初始化Bean时 添加请求拦截器
@EnableEurekaClient
@SpringBootApplication
//@EnableFeignClients //暂未使用
@Slf4j
public class ScbrlWebApplication {
······略
/**
* 实例化restTemplate
* 并使其拥有Ribbon负载均衡能力
* @return
*/
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
httpRequestFactory.setConnectionRequestTimeout(15);
httpRequestFactory.setConnectTimeout(15);
httpRequestFactory.setReadTimeout(15);
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters()
.add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
restTemplate.setInterceptors(Collections.singletonList(new RestUserAgentInterceptor()));
return restTemplate;
}
······略
}
大功告成,这样每次restTemplate请求都会进入RestUserAgentInterceptor,自动加上请求头信息