java 简单使用redis

1.配置文件

  <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="50" />
<property name="maxIdle" value="8" />
<property name="maxWaitMillis" value="1000" />
<property name="testOnBorrow" value="true"/>
<property name="testOnReturn" value="true"/>
</bean> <bean id="jedisPool" class="redis.clients.jedis.JedisPool">
<constructor-arg index="0" ref="jedisPoolConfig" />
<constructor-arg index="1" value="192.168.1.76" type="java.lang.String"/>
<constructor-arg index="2" value="6379" type="int"/>
</bean>

2.复杂对象,通过序列化成进进制存储到redis中

@Repository("RedisCacheImpl")
public class RedisCacheImpl implements IRedisCache { private static final Logger logger = LoggerFactory.getLogger(RedisCacheImpl.class); @Autowired(required = false)
protected JedisPool pool; @Override
public void put(String key, Object value) {
Jedis jedis = null;
try {
jedis = pool.getResource();
jedis.set(key.getBytes(), SerializeUtil.serialize(value));
} catch (Exception e) {
logger.error("redis error:", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
} @SuppressWarnings({"unchecked"})
@Override
public <T> T get(String key) {
Jedis jedis = null;
try {
jedis = pool.getResource();
byte[] value = jedis.get(key.getBytes());
if (value == null) {
return null;
}
return (T) SerializeUtil.unSerialize(value);
} catch (Exception e) {
logger.error("redis error:", e);
return null;
} finally {
if (jedis != null) {
jedis.close();
}
}
} @SuppressWarnings({"unchecked"})
@Override
public boolean del(String key) {
Jedis jedis = null;
try {
jedis = pool.getResource();
return jedis.del(key.getBytes()) > 0;
} catch (Exception e) {
logger.error("redis error:", e);
return false;
} finally {
if (jedis != null) {
jedis.close();
}
}
}
}

3.序列化类

public class SerializeUtil {

    private static final Logger logger = LoggerFactory.getLogger(SerializeUtil.class);

    public static byte[] serialize(Object object) {
ObjectOutputStream oos = null;
ByteArrayOutputStream baos = null;
try {
// 序列化
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
byte[] bytes = baos.toByteArray();
return bytes;
} catch (Exception e) {
logger.error("serializer error:", e);
}
return null;
} public static Object unSerialize(byte[] bytes) {
ByteArrayInputStream bais = null;
try {
// 反序列化
bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
return ois.readObject();
} catch (Exception e) {
logger.error("serializer error:", e);
}
return null;
}
}
上一篇:【转译】加入ZigBee联盟,共画物联网的未来


下一篇:js笔记——js里var与变量提升