这几天没事,就把之前学习的redis代码整理一遍,废话不多说,上步骤。
1、pom.xml引入资源;
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.7.0.RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.0</version>
</dependency>
2、配置redis的配置文件,这里只配置单点数据库,后面会介绍redis集群的配置,这里就不多说了;
spring-redis.xml配置:
<!-- 读取配置文件信息 -->
<context:property-placeholder ignore-unresolvable="true" location="classpath:*.properties"/>
<!-- Redis 配置 -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="${redis.maxActive}" />
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
<property name="testOnBorrow" value="true" />
</bean>
<!-- redis单节点数据库连接配置 -->
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="${redis.host}" />
<property name="port" value="${redis.port}" />
<property name="password" value="${redis.password}" />
<property name="poolConfig" ref="jedisPoolConfig" />
</bean>
<!-- redisTemplate配置,redisTemplate是对Jedis的对redis操作的扩展,有更多的操作,封装使操作更便捷 -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory" />
</bean>
redis.properties文件配置:
#redis的服务器地址
redis.host=这里写你的ip
#redis的服务端口
redis.port=6379
#密码
redis.password=这里写你的密码
#链接数据库
redis.default.db=0
#客户端超时时间单位是毫秒
redis.timeout=100000
#最大连接数
redis.maxActive=300
#最大空闲数
redis.maxIdle=100
#最大建立连接等待时间
redis.maxWaitMillis=1000
3、接着,具体实现代码;
序列化和反序列化工具类:
public class SerializerUtil { /** * 序列化 * @param object * @return */ public static byte[] serializeObj(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) { throw new RuntimeException("序列化失败!", e); } } /** * 反序列化 * @param bytes * @return */ public static Object deserializeObj(byte[] bytes) { if (bytes == null){ return null; } ByteArrayInputStream bais = null; try { bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); return ois.readObject(); } catch (Exception e) { throw new RuntimeException("反序列化失败!", e); } } }
操作实现类,这里只提供了3个实现方法,其他的可以按照自己需求自己实现:
@Component public class RedisCache { @Resource private RedisTemplate<String, String> redisTemplate; /** * 添加缓存数据 * @param key * @param obj * @param <T> * @return * @throws Exception */ public <T> boolean putCache(String key, T obj) throws Exception { final byte[] bkey = key.getBytes(); final byte[] bvalue = SerializerUtil.serializeObj(obj); boolean result = redisTemplate.execute(new RedisCallback<Boolean>() { @Override public Boolean doInRedis(RedisConnection connection) throws DataAccessException { return connection.setNX(bkey, bvalue); } }); return result; } /** * 添加缓存数据,设定缓存失效时间 * @param key * @param obj * @param expireTime * @param <T> * @throws Exception */ public <T> void putCacheWithExpireTime(String key, T obj, final long expireTime) throws Exception { final byte[] bkey = key.getBytes(); final byte[] bvalue = SerializerUtil.serializeObj(obj); redisTemplate.execute(new RedisCallback<Boolean>() { @Override public Boolean doInRedis(RedisConnection connection) throws DataAccessException { connection.setEx(bkey, expireTime, bvalue); return true; } }); } /** * 根据key取缓存数据 * @param key * @param <T> * @return * @throws Exception */ public <T> T getCache(final String key) throws Exception { byte[] result = redisTemplate.execute(new RedisCallback<byte[]>() { @Override public byte[] doInRedis(RedisConnection connection) throws DataAccessException { return connection.get(key.getBytes()); } }); if (result == null) { return null; } return (T) SerializerUtil.deserializeObj(result); } }
4、测试代码;
@Test public void test7() throws Exception{ List<String> list = new ArrayList<String>(); list.add("测试list"); list.add("测试list2"); Map<String,Object> map = new HashMap<String, Object>(); map.put("test*","测试数据"); map.put("测试数据","啥的"); map.put("listTest",list); redisCache.putCache("testMap",map); Map<String,Object> mapResult = redisCache.getCache("testMap"); System.out.print(mapResult.toString()); }
结果:
5、OK,一切正常。ps:有兴趣的同学可以去看看redis源码,挺好!