添加依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.0.1</version>
</dependency>
配置
applicationContext-jedis.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.xsd">
<!-- 连接池配置 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="200"></property>
</bean>
<!-- 创建分片式redis连接池 -->
<bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool">
<constructor-arg index="0" ref="poolConfig"></constructor-arg>
<constructor-arg index="1">
<list>
<bean class="redis.clients.jedis.JedisShardInfo">
<constructor-arg index="0" value="127.0.0.1"></constructor-arg>
<constructor-arg index="1" value="6379"></constructor-arg>
</bean>
</list>
</constructor-arg>
</bean>
</beans>
service层
JedisService.java
package com.nongmall.common.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
@Service
public class JedisService {
@Autowired
private ShardedJedisPool shardedJedisPool;
/**
* 存储值
* @param key
* @param value
*/
public void set (String key,String value){
ShardedJedis jedis = shardedJedisPool.getResource();
jedis.set(key, value);
}
/**
* 取值
* @param key
* @return
*/
public String get(String key){
ShardedJedis jedis = shardedJedisPool.getResource();
return jedis.get(key);
}
/**
* 删除
* @param key
*/
public void delete(String key){
ShardedJedis jedis = shardedJedisPool.getResource();
jedis.del(key);
}
/**
*根据键值设置存活时间
* @param key
* @param seconds
*/
public void expire(String key,int seconds){
ShardedJedis jedis = shardedJedisPool.getResource();
jedis.expire(key, seconds);
}
/**
* 存储值并且设置存活时间
* @param key
* @param seconds
* @param value
*/
public void setex(String key , int seconds , String value){
ShardedJedis jedis = shardedJedisPool.getResource();
jedis.setex(key, seconds, value);
}
}