==
@Service("redisMapServiceImpl1")
public class RedisMapServiceImpl {
@Autowired
private ShardedJedisPool shardedJedisPool;
private ShardedJedis shardedJedis;
public void put(Object k, Object v) {
getShardedJedis().set(this.ObjectToByte(k), this.ObjectToByte(v));
}
public <V> V get(Object key) {
return this.ByteToObject(getShardedJedis().get(this.ObjectToByte(key)));
}
public void remove(Object key) {
getShardedJedis().del(this.ObjectToByte(key));
}
private ShardedJedis getShardedJedis() {
if (shardedJedis == null) {
shardedJedis = shardedJedisPool.getResource();
}
return shardedJedis;
}
private <C> C ByteToObject(byte[] bytes) {
C obj = null;
try {
ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
ObjectInputStream oi = new ObjectInputStream(bi);
obj = (C) oi.readObject();
bi.close();
oi.close();
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
public byte[] ObjectToByte(Object obj) {
byte[] bytes = null;
try {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(bo);
oo.writeObject(obj);
bytes = bo.toByteArray();
bo.close();
oo.close();
} catch (Exception e) {
e.printStackTrace();
}
return bytes;
}
}
==
这个代码不够好,还在持续想办法优化中。。。。。(*^__^*) 嘻嘻……
上面的代码是流 然后是字符串的。
==
@Service("redisJsonMapServiceImpl")
public class RedisJsonMapServiceImpl implements RedisMapService {
@Autowired
private ShardedJedisPool shardedJedisPool;
private Jedis jedis;
public void put(String k, String vStr) {
getShardedJedis().set(k, vStr);
}
public void put(String k, Object vObj) {
ObjectMapper mapper = new ObjectMapper();
String json = null;
try {
json = mapper.writeValueAsString(vObj);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
this.put(k, json);
}
public void put(String k, int seconds, String vStr) {
getShardedJedis().setex(k, seconds, vStr);
}
public void put(String k, int seconds, Object vObj) {
ObjectMapper mapper = new ObjectMapper();
String json = null;
try {
json = mapper.writeValueAsString(vObj);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
this.put(k, seconds, json);
}
public <V> V get(String key, TypeReference<V> t) {
String s = getShardedJedis().get(key);
ObjectMapper mapper = new ObjectMapper();
V vo = null;
try {
vo = mapper.readValue(s, t);
} catch (Exception e) {
e.printStackTrace();
}
return vo;
}
public String get(String key) {
return getShardedJedis().get(key);
}
public void remove(String key) {
getShardedJedis().del(key);
}
public Set<String> getMatch(String pattern) {
return getShardedJedis().keys(pattern);
}
public Set<String> getKayAll() {
return getShardedJedis().keys("*");
}
private Jedis getShardedJedis() {
if (jedis == null) {
jedis = shardedJedisPool.getResource().getAllShards().iterator()
.next();
}
return jedis;
}
}
==