springboot整合ehcache,使用httpClient测试
一:springboot整合httpClient
- httpclient介绍
HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包
-
配置
1.添加依赖org.apache.httpcomponents httpclient 4.3.6 2.application配置
http: #最大连接数 maxTotal : 10 #最大并发数 defaultMaxPerRoute : 20 #客户端和服务器建立连接的超时时间 connectTimeout : 1000 #从连接池获取连接的超时时间 connectionRequestTimeout : 500 #从服务端读取数据超时时间 socketTimeout : 10000 staleConnectionCheckEnabled : true
3.编写配置
HttpClient核心功能分为http连接对象(HttpClient)的创建和连接信息配置(HttpRequestBase)
- 连接池管理器
- 连接构造器
- 连接配置信息
@Configuration
public class HttpClientConfig {
@Value("${http.maxTotal}")
private Integer maxTotal;
@Value("${http.defaultMaxPerRoute}")
private Integer defaultMaxPerRoute;
@Value("${http.connectTimeout}")
private Integer connectTimeout;
@Value("${http.connectionRequestTimeout}")
private Integer connectionRequestTimeout;
@Value("${http.socketTimeout}")
private Integer socketTimeout;
@Value("${http.staleConnectionCheckEnabled}")
private boolean staleConnectionCheckEnable;
/**
* httpClient连接池管理器
*
* @return
*/
@Bean(name = "httpClientPoolManager")
public PoolingHttpClientConnectionManager getHttpClientConnectionManager() {
PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();
poolingHttpClientConnectionManager.setMaxTotal(maxTotal);
poolingHttpClientConnectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
return poolingHttpClientConnectionManager;
}
/**
* httpClient连接池
* 连接构造器
* @param httpClientPoolManager
* @return
*/
@Bean(name = "httpClientBuilder")
public HttpClientBuilder httpClientBuilder(@Qualifier("httpClientPoolManager") PoolingHttpClientConnectionManager httpClientPoolManager) {
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
httpClientBuilder.setConnectionManager(httpClientPoolManager);
return httpClientBuilder;
}
/**
* httpClient bean
*
* @param httpClientBuilder
* @return
*/
@Bean
public CloseableHttpClient getCloseableHttpClient(@Qualifier("httpClientBuilder") HttpClientBuilder httpClientBuilder) {
return httpClientBuilder.build();
}
/**
* 内部配置类
*
* @return
*/
@Bean(name = "builder")
public RequestConfig.Builder getBuilder() {
RequestConfig.Builder builder = RequestConfig.custom();
return builder.setConnectTimeout(connectTimeout)
.setConnectionRequestTimeout(connectionRequestTimeout)
.setSocketTimeout(socketTimeout)
.setStaleConnectionCheckEnabled(staleConnectionCheckEnable);
}
/**
* HttpRequestBase所需的config
*/
@Bean
public RequestConfig getRequestConfig(@Qualifier("builder") RequestConfig.Builder builder) {
return builder.build();
}
}
4.httpclient工具类
@Service
public class HttpAPIService {
@Autowired
private CloseableHttpClient httpClient;
@Autowired
private RequestConfig config;
/**
* 不带参数的get请求,如果状态码为200,则返回body,如果不为200,则返回null
*
* @param url
* @return
* @throws Exception
*/
public String doGet(String url) throws Exception {
// 声明 http get 请求
HttpGet httpGet = new HttpGet(url);
// 装载配置信息
httpGet.setConfig(config);
// 发起请求
CloseableHttpResponse response = this.httpClient.execute(httpGet);
// 判断状态码是否为200
if (response.getStatusLine().getStatusCode() == 200) {
// 返回响应体的内容
return EntityUtils.toString(response.getEntity(), "UTF-8");
}
return null;
}
/**
* 带参数的get请求,如果状态码为200,则返回body,如果不为200,则返回null
*
* @param url
* @return
* @throws Exception
*/
public String doGet(String url, Map map) throws Exception {
URIBuilder uriBuilder = new URIBuilder(url);
if (map != null) {
// 遍历map,拼接请求参数
for (Map.Entry entry : map.entrySet()) {
uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
}
}
// 调用不带参数的get请求
return this.doGet(uriBuilder.build().toString());
}
/**
* 带参数的post请求
*
* @param url
* @param map
* @return
* @throws Exception
*/
public HttpResult doPost(String url, Map map) throws Exception {
// 声明httpPost请求
HttpPost httpPost = new HttpPost(url);
// 加入配置信息
httpPost.setConfig(config);
// 判断map是否为空,不为空则进行遍历,封装from表单对象
if (map != null) {
List list = new ArrayList();
for (Map.Entry entry : map.entrySet()) {
list.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
// 构造from表单对象
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, "UTF-8");
// 把表单放到post里
httpPost.setEntity(urlEncodedFormEntity);
}
// 发起请求
CloseableHttpResponse response = this.httpClient.execute(httpPost);
return new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(
response.getEntity(), "UTF-8"));
}
/**
* 不带参数post请求
*
* @param url
* @return
* @throws Exception
*/
public HttpResult doPost(String url) throws Exception {
return this.doPost(url, null);
}
}
二:springboot整合ehcache
- ehcache介绍
Ehcache是用来管理缓存的工具,缓存数据可以存放在内存也可以存放在硬盘。
其核心是CacheManager,一切Ehcache的应用都是从CacheManager开始的。它是用来管理Cache(缓存)的,一个应用可以有多个CacheManager,而一个CacheManager下又可以有多个Cache。Cache内部保存的是一个个的Element,而一个Element中保存的是一个key和value的配对,相当于Map里面的一个Entry。
优缺点:ehcache直接在jvm虚拟机中缓存,速度快,效率高;但是缓存共享麻烦,集群分布式应用不方便。
ehcache也有缓存共享方案,不过是通过RMI或者Jgroup多播方式进行广播缓存通知更新,缓存共享复杂,维护不方便;简单的共享可以,但是涉及到缓存恢复,大数据缓存,则不合适。
- 配置
1.添加依赖
org.springframework.boot
spring-boot-starter-cache
net.sf.ehcache
ehcache
2.自定义EhCache配置
classpath config下添加ehcache.xml
3.application配置
spring:
#缓存配置
cache:
type: ehcache
ehcache:
config: classpath:config/ehcache.xml
-
测试使用
这里我使用硬编码的写了个UserService来接受请求。这里使用HttpClient方式对本地服务做请求。Controller代码片段 @Controller @RequestMapping(value = "/test") public class TestController { private static Logger log = LoggerFactory.getLogger(TestController.class); @Autowired private HttpClientUtil httpClientUtil ; @RequestMapping("/cache") public void testCache() throws Exception{ for(int i=0;i<22;i++){//连续请求,根据Ehcache的timeToLiveSeconds配置20秒缓存失效 log.debug("times {}",i); Thread.sleep(1000); log.debug(httpClientUtil .doGet("http://localhost:8081/user/get?id=1")); } }
}
Service代码片段 @Override @Cacheable(key = "#id",value="cache1") public User findById(Integer id) { User user = new User(); user.setId(LocalTime.now().getSecond());//用于测试 user.setUsername("test"); user.setPassword("111111"); return user; }