spring中整合memcached,以及创建memcache的put和get方法:
1:在项目中导入memcache相关的jar包
2:memcache在spring.xml的配置:
代码:
1 26 7 8 20 219 10 11 1312 14 1615 17 1918 22 2423
3:memcache在db.properties中的配置:
4:在spring的主配置文件中引入memcache的相关配置:
5:自己封装好的memcache方法(get(), put(), flushAll() )
1 package com.floor.shop.map; 2 3 import net.rubyeye.xmemcached.MemcachedClient; 4 import net.rubyeye.xmemcached.exception.MemcachedException; 5 6 import java.util.concurrent.TimeoutException; 7 8 public class MemcachedAccess { 9 private MemcachedClient memcachedClient;10 /*11 * 将memcachedClient交给spring管理12 * (就需提供下面的get和set方法)13 */14 public MemcachedClient getMemcachedClient() {15 return memcachedClient;16 }17 18 public void setMemcachedClient(MemcachedClient memcachedClient) {19 this.memcachedClient = memcachedClient;20 }21 22 /*23 * memcache基于HashMap所以通过key,value的形式放值和取值。24 * memcachedClient提供了add方法进行放值,add方法需要传递三个参数String var1, int var2, Object var325 * 分别表示:var1:key; var2:缓存的时间; var3:key对应的值26 * 对外提供put方法往memcache里面放值:27 */28 public boolean put(String key, Integer time, String value) {29 try {30 boolean add = memcachedClient.add(key, time, value);31 return add;32 } catch (TimeoutException e) {33 e.printStackTrace();34 } catch (InterruptedException e) {35 e.printStackTrace();36 } catch (MemcachedException e) {37 e.printStackTrace();38 }39 return false;40 }41 42 /*43 *如果把时间写成死的数据:1天,就不需要传时间进来44 * memcache的缓存时间是以秒为单位,默认缓存好像是一个月。45 */46 public boolean put(String key , String value) {47 try {48 boolean add = memcachedClient.add(key, 1*24*60, value);49 return add;50 } catch (TimeoutException e) {51 e.printStackTrace();52 } catch (InterruptedException e) {53 e.printStackTrace();54 } catch (MemcachedException e) {55 e.printStackTrace();56 }57 return false;58 }59 60 /*61 * 对外提供取值的get方法62 */63 public String get(String key){64 try {65 String value = (String)memcachedClient.get(key);66 return value;67 } catch (TimeoutException e) {68 e.printStackTrace();69 } catch (InterruptedException e) {70 e.printStackTrace();71 } catch (MemcachedException e) {72 e.printStackTrace();73 }74 return null;75 }76 77 //对外提供清除所有缓存的方法:78 public void flushAll(){79 try {80 memcachedClient.flushAll();81 } catch (TimeoutException e) {82 e.printStackTrace();83 } catch (InterruptedException e) {84 e.printStackTrace();85 } catch (MemcachedException e) {86 e.printStackTrace();87 }88 }89 90 }