1.RedisTemplate介绍
Spring为了更加方便操作redis,对redis操作进行封装,maven依赖如下:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.8.18.RELEASE</version>
</dependency>
RedisTemplate是Spring封装用来操作redis的模板工具类,封装了我们常用的redis操作,例如:set、get、hset、hget等
2.如何获取Jedis实例
2.1 背景
redis实现分布式锁,其中需要Jedis实例,其中核心用到的Jedis#set()方法如下:
/**
* Set the string value as value of the key. The string can't be longer than 1073741824 bytes (1
* GB).
* @param key
* @param value
* @param nxxx NX|XX, NX -- Only set the key if it does not already exist. XX -- Only set the key
* if it already exist.
* @param expx EX|PX, expire time units: EX = seconds; PX = milliseconds
* @param time expire time in the units of <code>expx</code>
* @return Status code reply
*/
public String set(final String key, final String value, final String nxxx, final String expx,
final long time) {
checkIsInMultiOrPipeline();
client.set(key, value, nxxx, expx, time);
return client.getStatusCodeReply();
}
2.2 Spring集成redis配置文件
1.单机部署
redis-config.xml文件如下 :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<!-- jedis 配置 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="minIdle" value="${jedis.pool.minIdle}"/>
<property name="maxIdle" value="${jedis.pool.maxIdle}"/>
<property name="maxTotal" value="${jedis.pool.maxTotal}"/>
<property name="maxWaitMillis" value="${jedis.pool.maxWaitMillis}"/>
<