CacheController:
package com..cache.googleCache; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Controller public class CacheController { @RequestMapping("/setCache") public void setCache(HttpServletRequest request, HttpServletResponse response) throws IOException { String id = request.getParameter("id"); String name = request.getParameter("name"); LocalCache.setKey(id,name); response.getWriter().print(id+"----"+name); } @RequestMapping("/getCache") public void getCache(HttpServletRequest request, HttpServletResponse response) throws IOException { String id = request.getParameter("id"); Object result = LocalCache.getKey(id); response.getWriter().print(result.toString()); } }
具体方法:
package com..cache.googleCache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; public class LocalCache { private static LoadingCache<String, Object> localCache = CacheBuilder.newBuilder() .initialCapacity(100) .maximumSize(10000) //指定时间内没有被创建覆盖,则指定时间过后,再次访问时,会去刷新该缓存,在新值没有到来之前,始终返回旧值 .refreshAfterWrite(12, TimeUnit.HOURS) .build(new CacheLoader<String, Object>() { @Override public String load(String s) { return "null"; } }); /** * @param key key * @param value value */ public static void setKey(String key, Object value) { System.out.println("==> Cache.setKey [key:{} value:{}]"+ key+"----"+ value); localCache.put(key, value);for (String s:localCache.asMap().keySet()) { try { System.err.println(s+"+++111::"+localCache.get(s)); } catch (ExecutionException e) { e.printStackTrace(); } } } /** * * @param key key * @return Object */ public static Object getKey(String key) { try { Object value = localCache.get(key); if ("null".equals(value)) { return null; } return value; } catch (Exception e) { e.getMessage(); } return null; } }
模拟调用:
public static void main(String[] args) { // String url = "http://localhost:8080/setCache?id=1&name=li"; String url = "http://localhost:8080/getCache?id=2"; String res = getStringData(url, ""); System.out.println(res); } public static String getStringData(String url,String data) { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); try { httpPost.setEntity(new StringEntity(data)); HttpResponse response = httpClient.execute(httpPost); String Str = EntityUtils .toString(response.getEntity()); return Str; } catch (Exception e) { e.printStackTrace(); return null; } }