小伙伴们,我开了一家海淘护肤品淘宝店,搜索店铺“禾子蝶的海淘铺”,正品保证,欢迎进店选购哦。谢谢!
Google Guava Cache:本地缓存实现,支持多种缓存过期策略,具体看官网:http://ifeve.com/google-guava/
使用案例:
1:先依赖guava的jar包
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
2:添加配置文件VcodeCacheManager.java
package com.cmcc.util;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
public class VcodeCacheManager {
public static Cache<String, String> cacheTicket = CacheBuilder.newBuilder().expireAfterWrite(7200, TimeUnit.SECONDS) // 过期时间7200s,TimeUnit.SECONDS可改
.maximumSize(1000)// 最大缓存数量
.build();
public static String getTicket(String key) {
if(key == null){
return "";
}
try {
return cacheTicket.get(key, new Callable<String>() {
public String call() throws Exception {
return "";
}
});
} catch (ExecutionException e) {
}
return null;
}
public static void putTicket(String key, String value) {
cacheTicket.put(key, value);
}
public static void remove(String key) {
cacheTicket.invalidate(key);
}
}
3:使用由于微信的分享使用有效期为7200s,需要将所需的ticket的值放到cacheTicket缓存中,过期后就更新ticket值,这样每次取到ticket都是有效的。
package com.cmcc.controller.rest.share;
import java.io.IOException;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.cmcc.util.Constant;
import com.cmcc.util.StringUtil;
import com.cmcc.util.VcodeCacheManager;
import com.cmcc.util.alipay.util.httpClient.HttpProtocolHandler;
import com.cmcc.util.alipay.util.httpClient.HttpRequest;
import com.cmcc.util.alipay.util.httpClient.HttpResponse;
import com.cmcc.util.alipay.util.httpClient.HttpResultType;
@RestController
@RequestMapping(value = "/share")
public class ShareController {
@RequestMapping(value = "/shareOthers", method = RequestMethod.GET)
public @ResponseBody String shareContent() throws HttpException, IOException {
String ticketResult;
String ticketVal = VcodeCacheManager.getTicket("ticket");
if(StringUtil.isEmpty(ticketVal)){
HttpRequest request = new HttpRequest(HttpResultType.BYTES);
//设置编码集
request.setCharset(Constant.CHARSET);
request.setMethod(HttpRequest.METHOD_GET);
request.setUrl(Constant.TOKEN_URL);
request.setQueryString("grant_type=client_credential"+"&appid="+Constant.APPID+"&secret="+Constant.APPSECRET);
HttpResponse response;
HttpProtocolHandler httpProtocolHandler = HttpProtocolHandler.getInstance();
response = httpProtocolHandler.execute(request,"","");
String tokenStr = response.getStringResult();
JSONObject tokenObj = JSONObject.fromObject(tokenStr);
String accessToken = (String) tokenObj.get("access_token");
//accessToken用于查询ticket。
request.setUrl(Constant.TICKET_URL);
request.setQueryString("access_token="+accessToken+"&type=jsapi");
response = httpProtocolHandler.execute(request,"","");
String ticketStr = response.getStringResult();
JSONObject ticketObj = JSONObject.fromObject(ticketStr);
String ticket = (String) ticketObj.get("ticket");
VcodeCacheManager.putTicket("ticket", ticket);
ticketResult=ticket;
}else{
ticketResult=ticketVal;
}
return ticketResult;
}
}
package com.cmcc.util.alipay.util.httpClient;
import org.apache.commons.httpclient.NameValuePair;
/* *
*类名:HttpRequest
*功能:Http请求对象的封装
*详细:封装Http请求
*版本:3.3
*日期:2011-08-17
*说明:
*以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己网站的需要,按照技术文档编写,并非一定要使用该代码。
*该代码仅供学习和研究支付宝接口使用,只是提供一个参考。
*/
说明:HttpRequest用于request请求
public class HttpRequest {
/** HTTP GET method */
public static final String METHOD_GET = "GET";
/** HTTP POST method */
public static final String METHOD_POST = "POST";
/**
* 待请求的url
*/
private String url = null;
/**
* 默认的请求方式
*/
private String method = METHOD_POST;
private int timeout = 0;
private int connectionTimeout = 0;
/**
* Post方式请求时组装好的参数值对
*/
private NameValuePair[] parameters = null;
/**
* Get方式请求时对应的参数
*/
private String queryString = null;
/**
* 默认的请求编码方式
*/
private String charset = "GBK";
/**
* 请求发起方的ip地址
*/
private String clientIp;
/**
* 请求返回的方式
*/
private HttpResultType resultType = HttpResultType.BYTES;
public HttpRequest(HttpResultType resultType) {
super();
this.resultType = resultType;
}
/**
* @return Returns the clientIp.
*/
public String getClientIp() {
return clientIp;
}
/**
* @param clientIp The clientIp to set.
*/
public void setClientIp(String clientIp) {
this.clientIp = clientIp;
}
public NameValuePair[] getParameters() {
return parameters;
}
public void setParameters(NameValuePair[] parameters) {
this.parameters = parameters;
}
public String getQueryString() {
return queryString;
}
public void setQueryString(String queryString) {
this.queryString = queryString;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public int getConnectionTimeout() {
return connectionTimeout;
}
public void setConnectionTimeout(int connectionTimeout) {
this.connectionTimeout = connectionTimeout;
}
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
/**
* @return Returns the charset.
*/
public String getCharset() {
return charset;
}
/**
* @param charset The charset to set.
*/
public void setCharset(String charset) {
this.charset = charset;
}
public HttpResultType getResultType() {
return resultType;
}
public void setResultType(HttpResultType resultType) {
this.resultType = resultType;
}
}
说明:HttpProtocolHandler类是用于Response回复
package com.cmcc.util.alipay.util.httpClient;
import org.apache.commons.httpclient.HttpException;
import java.io.IOException;
import java.net.UnknownHostException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.util.IdleConnectionTimeoutThread;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.FilePartSource;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.httpclient.params.HttpMethodParams;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/* *
*类名:HttpProtocolHandler
*功能:HttpClient方式访问
*详细:获取远程HTTP数据
*版本:3.3
*日期:2012-08-17
*说明:
*以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己网站的需要,按照技术文档编写,并非一定要使用该代码。
*该代码仅供学习和研究支付宝接口使用,只是提供一个参考。
*/
public class HttpProtocolHandler {
private static String DEFAULT_CHARSET = "GBK";
/** 连接超时时间,由bean factory设置,缺省为8秒钟 */
private int defaultConnectionTimeout = 8000;
/** 回应超时时间, 由bean factory设置,缺省为30秒钟 */
private int defaultSoTimeout = 30000;
/** 闲置连接超时时间, 由bean factory设置,缺省为60秒钟 */
private int defaultIdleConnTimeout = 60000;
private int defaultMaxConnPerHost = 30;
private int defaultMaxTotalConn = 80;
/** 默认等待HttpConnectionManager返回连接超时(只有在达到最大连接数时起作用):1秒*/
private static final long defaultHttpConnectionManagerTimeout = 3 * 1000;
/**
* HTTP连接管理器,该连接管理器必须是线程安全的.
*/
private HttpConnectionManager connectionManager;
private static HttpProtocolHandler httpProtocolHandler = new HttpProtocolHandler();
/**
* 工厂方法
*
* @return
*/
public static HttpProtocolHandler getInstance() {
return httpProtocolHandler;
}
/**
* 私有的构造方法
*/
private HttpProtocolHandler() {
// 创建一个线程安全的HTTP连接池
connectionManager = new MultiThreadedHttpConnectionManager();
connectionManager.getParams().setDefaultMaxConnectionsPerHost(defaultMaxConnPerHost);
connectionManager.getParams().setMaxTotalConnections(defaultMaxTotalConn);
IdleConnectionTimeoutThread ict = new IdleConnectionTimeoutThread();
ict.addConnectionManager(connectionManager);
ict.setConnectionTimeout(defaultIdleConnTimeout);
ict.start();
}
/**
* 执行Http请求
*
* @param request 请求数据
* @param strParaFileName 文件类型的参数名
* @param strFilePath 文件路径
* @return
* @throws HttpException, IOException
*/
public HttpResponse execute(HttpRequest request, String strParaFileName, String strFilePath) throws HttpException, IOException {
HttpClient httpclient = new HttpClient(connectionManager);
// 设置连接超时
int connectionTimeout = defaultConnectionTimeout;
if (request.getConnectionTimeout() > 0) {
connectionTimeout = request.getConnectionTimeout();
}
httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);
// 设置回应超时
int soTimeout = defaultSoTimeout;
if (request.getTimeout() > 0) {
soTimeout = request.getTimeout();
}
httpclient.getHttpConnectionManager().getParams().setSoTimeout(soTimeout);
// 设置等待ConnectionManager释放connection的时间
httpclient.getParams().setConnectionManagerTimeout(defaultHttpConnectionManagerTimeout);
String charset = request.getCharset();
charset = charset == null ? DEFAULT_CHARSET : charset;
HttpMethod method = null;
//get模式且不带上传文件
if (request.getMethod().equals(HttpRequest.METHOD_GET)) {
method = new GetMethod(request.getUrl());
method.getParams().setCredentialCharset(charset);
// parseNotifyConfig会保证使用GET方法时,request一定使用QueryString
method.setQueryString(request.getQueryString());
} else if(strParaFileName.equals("") && strFilePath.equals("")) {
//post模式且不带上传文件
method = new PostMethod(request.getUrl());
((PostMethod) method).addParameters(request.getParameters());
method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; text/html; charset=" + charset);
}
else {
//post模式且带上传文件
method = new PostMethod(request.getUrl());
List<Part> parts = new ArrayList<Part>();
for (int i = 0; i < request.getParameters().length; i++) {
parts.add(new StringPart(request.getParameters()[i].getName(), request.getParameters()[i].getValue(), charset));
}
//增加文件参数,strParaFileName是参数名,使用本地文件
parts.add(new FilePart(strParaFileName, new FilePartSource(new File(strFilePath))));
// 设置请求体
((PostMethod) method).setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[0]), new HttpMethodParams()));
}
// 设置Http Header中的User-Agent属性
method.addRequestHeader("User-Agent", "Mozilla/4.0");
HttpResponse response = new HttpResponse();
try {
httpclient.executeMethod(method);
if (request.getResultType().equals(HttpResultType.STRING)) {
response.setStringResult(method.getResponseBodyAsString());
} else if (request.getResultType().equals(HttpResultType.BYTES)) {
response.setByteResult(method.getResponseBody());
}
response.setResponseHeaders(method.getResponseHeaders());
} catch (UnknownHostException ex) {
return null;
} catch (IOException ex) {
return null;
} catch (Exception ex) {
return null;
} finally {
method.releaseConnection();
}
return response;
}
/**
* 将NameValuePairs数组转变为字符串
*
* @param nameValues
* @return
*/
protected String toString(NameValuePair[] nameValues) {
if (nameValues == null || nameValues.length == 0) {
return "null";
}
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < nameValues.length; i++) {
NameValuePair nameValue = nameValues[i];
if (i == 0) {
buffer.append(nameValue.getName() + "=" + nameValue.getValue());
} else {
buffer.append("&" + nameValue.getName() + "=" + nameValue.getValue());
}
}
return buffer.toString();
}
}
小伙伴们,我开了一家海淘护肤品淘宝店,搜索店铺“禾子蝶的海淘铺”,正品保证,欢迎进店选购哦。谢谢!
相关推荐
主要介绍了SpringBoot加入Guava Cache实现本地缓存代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
Guava-Cache本地缓存案例代码,包含:缓存创建、缓存删除、缓存获取、缓存失效监听器、缓存加载、缓存淘汰策略。
Springboot集成本地缓存Guava本章介绍一个比较好用的本地缓存Guava0x01、添加依赖0x02、添加GuavaLocalCache提供了设置超时时
使用google guava 实现定时缓存功能
主要介绍了springboot整合GuavaCache缓存过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
标签:google、guava、jar包、java、中英对照文档; 使用方法:解压翻译后的API文档,用浏览器打开“index.html”文件,即可纵览文档内容。 人性化翻译,文档中的代码和结构保持不变,注释和说明精准翻译,请放心...
Guava Cache是一个全内存的本地缓存实现,本文将讲述如何将 Guava Cache缓存应用到 Spring Boot应用中。具有一定的参考价值,感兴趣的小伙伴们可以参考一下
但是如果查询并发量特别大的话,请求redis服务也会特别耗时,这种场景下,将redis迁移到本地减少查询耗时是一种常见的解决方法项目结构说明double-cache-web 应用模块,请求入口double-cache-service 业务层模块...
标签:google、guava、中英对照文档、jar包、java; 使用方法:解压翻译后的API文档,用浏览器打开“index.html”文件,即可纵览文档内容。 人性化翻译,文档中的代码和结构保持不变,注释和说明精准翻译,请放心...
标签:google、guava、jar包、java、中文文档; 使用方法:解压翻译后的API文档,用浏览器打开“index.html”文件,即可纵览文档内容。 人性化翻译,文档中的代码和结构保持不变,注释和说明精准翻译,请放心使用。
Local caching - Guava Cache在Go中的部分的实现
第七章 企业项目开发--本地缓存guava cache1、在实际项目开发中,会使用到很多缓存技术,而且数据库的设计一般也会依赖于有缓存的情况下设计。常用的缓存分
对应Maven信息:groupId:com.google.guava,artifactId:guava,version:18.0 使用方法:解压翻译后的API文档,用浏览器打开“index.html”文件,即可纵览文档内容。 人性化翻译,文档中的代码和结构保持不变,...
主要介绍了springboot使用GuavaCache做简单缓存处理的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
google的guava工具包很实用,包括之前的字符串处理工具类的,还有大量的collection相关的
《有了Redis缓存就高枕无忧了?可别忘了本地缓存!》博客附件。 博客地址:https://blog.csdn.net/Supreme_Sir/article/details/115450798
springboot本地缓存(guava与caffeine).docx
├─Google Guava 第01讲-Joiner详细介绍以及和Java8Collector对比.wmv ├─Google Guava 第02讲-Guava Splitter详细讲解以及实战练习...├─Google Guava 第34讲-Guava Cache之RecordStats,CacheBuilderSpec详解.wmv
标签:google、guava、中文文档、jar包、java; 使用方法:解压翻译后的API文档,用浏览器打开“index.html”文件,即可纵览文档内容。 人性化翻译,文档中的代码和结构保持不变,注释和说明精准翻译,请放心使用。
标签:google、guava、中文文档、jar包、java; 使用方法:解压翻译后的API文档,用浏览器打开“index.html”文件,即可纵览文档内容。 人性化翻译,文档中的代码和结构保持不变,注释和说明精准翻译,请放心使用。