一、添加pom
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.6.0.RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.7.2</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.4.2</version>
</dependency>
二、在config.properties中添加redis配置参数
#redis配置信息
redis.host=127.0.0.1
#指定Redis监听端口,默认端口为6379
redis.port=6379
#授权密码(本例子没有使用)
redis.password=
#最大空闲数:空闲链接数大于maxIdle时,将进行回收
redis.maxIdle=100
#最大等待时间:单位ms
redis.maxWait=1000
#使用连接时,检测连接是否成功
redis.testOnBorrow=true
redis.maxTotal=600
redis.testOnReturn=true
三、在application.xml中添加redis配置
<!--redis配置-->
<!--设置连接池-->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}"/>
<property name="maxTotal" value="${redis.maxTotal}" />
<property name="maxWaitMillis" value="${redis.maxWait}" />
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
<property name="testOnReturn" value="${redis.testOnReturn}" />
</bean>
<!--设置链接属性-->
<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:hostName="${redis.host}"
p:port="${redis.port}"
p:password="${redis.password}"
p:pool-config-ref="poolConfig"
p:timeout="100000"/>
<!-- Jedis模板配置 -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
<property name="connectionFactory" ref="connectionFactory" />
</bean>
四、创建test测试类
@RunWith(SpringRunner.class)
@ContextConfiguration({"classpath:application.xml"})
public class RedisTest {
@Autowired
private RedisTemplate redisTemplate;
private static final Logger log = Logger.getLogger(RedisTest.class.getName());
@Test
public void test(){
redisTemplate.opsForValue().set("key", "key对应的值");
log.info("value:"+redisTemplate.opsForValue().get("key"));
}
}
五、启动测试类