Google Guava Cache: local cache, expired implementation

Google Guava Cache: Local cache implementation, supports multiple cache expiration strategies, see the official website for details: http://ifeve.com/google-guava/

Use Cases:

1: First depend on the jar package of guava

<dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>18.0</version>
 </dependency>

2: Add configuration file 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: Use due to WeChat sharing and use valid for 7200s, you need to put the value of the required ticket in the cacheTicket cache, and update the ticket value after it expires, so that the ticket is valid every time you get it.

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;

/* *
 *Class name: HttpRequest
 *Function: Encapsulation of Http request object
 *Details: Encapsulate Http request
 *Version: 3.3
 *Date: 2011-08-17
 *Description:
 *The following code is just a sample code provided for the convenience of merchants' testing. Merchants can write according to the needs of their own websites and according to the technical documents, but it is not necessary to use this code.
 *This code is only for learning and researching the Alipay interface, it is just a reference.
 */
Description: HttpRequest is used for 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 to be requested
     */
    private String url = null;

    /**
     * The default request method
     */
    private String method = METHOD_POST;

    private int timeout = 0;

    private int connectionTimeout = 0;

    /**
     * The assembled parameter value pair when requesting in Post method
     */
    private NameValuePair[] parameters = null;

    /**
     * The corresponding parameters of the Get request method
     */
    private String queryString = null;

    /**
     * The default request encoding method
     */
    private String charset = "GBK";

    /**
     * The ip address of the request initiator
     */
    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;
    }

}

Description: HttpProtocolHandler class is used for Response reply

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;

/* *
 *class name : HttpProtocolHandler
 *Function: HttpClient access
 *Details: Get remote HTTP data
 *Version: 3.3
 *Date: 2012-08-17
 *Description:
 *The following code is just a sample code for the convenience of merchants to test, merchants can use their own website According to the needs of the technical documentation, it is not necessary to use the code.
 *This code is only for learning and researching the Alipay interface, it is just a reference.
 */

public class HttpProtocolHandler {

    private static String DEFAULT_CHARSET = "GBK";

    /** Connection timeout, set by bean factory, default is 8 seconds*/
    private int defaultConnectionTimeout = 8000;

    /** Response timeout, set by bean factory , the default is 30 seconds */
    private int defaultSoTimeout = 30000;

    /** idle connection timeout, set by the bean factory, the default is 60 seconds */
    private int defaultIdleConnTimeout = 60000;

    private int defaultMaxConnPerHost = 30;

    private int defaultMaxTotalConn = 80;

    /** Default waiting for HttpConnectionManager to return connection timeout (only works when the maximum number of connections is reached): 1 second*/
    private static final long defaultHttpConnectionManagerTimeout = 3 * 1000;

    /**
     * HTTP connection manager, which must be thread-safe.
     */
    private HttpConnectionManager connectionManager;

    private static HttpProtocolHandler httpProtocolHandler = new HttpProtocolHandler();

    /**
     * Factory Method
     *
     * @return
     */
    public static HttpProtocolHandler getInstance() {
        return httpProtocolHandler;
    }

    /**
     * Private constructor
     */
    private HttpProtocolHandler() {
        // Create a thread-safe HTTP connection pool
        connectionManager = new MultiThreadedHttpConnectionManager();
        connectionManager.getParams().setDefaultMaxConnectionsPerHost(defaultMaxConnPerHost);
        connectionManager.getParams().setMaxTotalConnections(defaultMaxTotalConn);

        IdleConnectionTimeoutThread ict = new IdleConnectionTimeoutThread();
        ict.addConnectionManager(connectionManager);
        ict.setConnectionTimeout(defaultIdleConnTimeout);

        ict.start();
    }

    /**
     * Execute Http request
     *
     * @param request request data
     * @param strParaFileName file type parameter name
     * @param strFilePath file path
     * @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);

        // Set the time to wait for ConnectionManager to release the connection
        httpclient.getParams().setConnectionManagerTimeout(defaultHttpConnectionManagerTimeout);

        String charset = request.getCharset();
        charset = charset == null ? DEFAULT_CHARSET : charset;
        HttpMethod method = null;

        //get mode without upload file
        if (request.getMethod().equals(HttpRequest.METHOD_GET)) {
            method = new GetMethod(request.getUrl());
            method.getParams ().setCredentialCharset(charset);

            // parseNotifyConfig will ensure that when using the GET method, the request must use 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));
            }
            //Add file parameters, strParaFileName is the parameter name, use the local file
            parts.add(new FilePart(strParaFileName, new FilePartSource(new File(strFilePath))));
           
            // set the request body
            ((PostMethod) method).setRequestEntity( new MultipartRequestEntity(parts.toArray(new Part[0]), new HttpMethodParams()));
        }

        // Set the User-Agent property in Http Header
        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();
    }
}

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326655264&siteId=291194637