1.引入依赖
在pom.xml文件中的dependencies标签下引入如下依赖
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<!-- redis end -->
2.引入redis.properties文件
#redis配置开始
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=192.168.0.127
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=1024
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=10000
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=200
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=10000
#redis配置结束
spring.redis.block-when-exhausted=true
3.创建RedisCofig类来读取redis配置,并初始化连接池
import com.xjj.oa2015.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
/**
* redis配置类
* @author xingzq <250863062@qq.com>
* @date 2019/9/2
*/
//配置spring启动的时候加载
@Configuration
@PropertySource("classpath:redis.properties")
@Slf4j
public class RedisConfig {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.timeout}")
private int timeout;
@Value("${spring.redis.jedis.pool.max-idle}")
private int maxIdle;
@Value("${spring.redis.jedis.pool.max-wait}")
private long maxWaitMillis;
@Value("${spring.redis.password}")
private String password;
@Value("${spring.redis.block-when-exhausted}")
private boolean blockWhenExhausted;
@Bean
public JedisPool redisPoolFactory() throws Exception{
log.info("JedisPool注入成功!!");
log.info("redis地址:" + host + ":" + port);
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxIdle(maxIdle);
jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
// 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
jedisPoolConfig.setBlockWhenExhausted(blockWhenExhausted);
// 是否启用pool的jmx管理功能, 默认true
jedisPoolConfig.setJmxEnabled(true);
JedisPool jedisPool;
if(!StringUtils.isEmpty(password)){
jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password);
}else{
jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout);
}
return jedisPool;
}
}
4.创建RedisUtil类
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.BinaryClient;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.SortingParams;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Redis工具类
* @author xingzq <250863062@qq.com>
* @date 2019/9/2
* @version 1.1 (GitHub文档: https://github.com/whvcse/RedisUtil )
*/
//使用标签的形式将该类注入到spring容器中
@Component("redisUtil")
@Slf4j
public class RedisUtil {
public static final Integer DEFAULT_DB_INDEX = 0;
@Autowired
private JedisPool jedisPool;
/**
* <p>
* 通过key获取储存在redis中的value
* </p>
* <p>
* 并释放连接
* </p>
*
* @param key
* @param indexdb 选择redis库 0-15
* @return 成功返回value 失败返回null
*/
public String get(String key,int indexdb) {
Jedis jedis = null;
String value = null;
try {
jedis = jedisPool.getResource();
jedis.select(indexdb);
value = jedis.get(key);
log.info(value);
} catch (Exception e) {
log.error(e.getMessage());
} finally {
returnResource(jedisPool, jedis);
}
return value;
}
/**
* <p>
* 通过key获取储存在redis中的value (使用默认数据库,索引为 DEFAULT_DB_INDEX)
* </p>
* <p>
* 并释放连接
* </p>
*
* @param key
* @return 成功返回value 失败返回null
*/
public String get(String key) {
return get(key,DEFAULT_DB_INDEX);
}
/**
* <p>
* 通过key获取储存在redis中的value
* </p>
* <p>
* 并释放连接
* </p>
*
* @param key
* @param indexdb 选择redis库 0-15
* @return 成功返回value 失败返回null
*/
public byte[] get(byte[] key,int indexdb) {
Jedis jedis = null;
byte[] value = null;
try {
jedis = jedisPool.getResource();
jedis.select(indexdb);
value = jedis.get(key);
} catch (Exception e) {
log.error(e.getMessage());
} finally {
returnResource(jedisPool, jedis);
}
return value;
}
/**
* <p>
* 向redis存入key和value,并释放连接资源
* </p>
* <p>
* 如果key已经存在 则覆盖
* </p>
*
* @param key
* @param value
* @param indexdb 选择redis库 0-15
* @return 成功 返回OK 失败返回 0
*/
public String set(String key, String value,int indexdb) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.select(indexdb);
return jedis.set(key, value);
} catch (Exception e) {
log.error(e.getMessage());
return "0";
} finally {
returnResource(jedisPool, jedis);
}
}
/**
* <p>
* 向redis存入key和value,并释放连接资源(使用默认数据库,索引为 DEFAULT_DB_INDEX)
* </p>
* <p>
* 如果key已经存在 则覆盖
* </p>
*
* @param key
* @param value
* @return 成功 返回OK 失败返回 0
*/
public String set(String key, String value) {
return set(key, value, DEFAULT_DB_INDEX);
}
/**
* <p>
* 向redis存入key和value,并释放连接资源
* </p>
* <p>
* 如果key已经存在 则覆盖
* </p>
*
* @param key
* @param value
* @param indexdb 选择redis库 0-15
* @return 成功 返回OK 失败返回 0
*/
public String set(byte[] key, byte[] value,int indexdb) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.select(indexdb);
return jedis.set(key, value);
} catch (Exception e) {
log.error(e.getMessage());
return "0";
} finally {
returnResource(jedisPool, jedis);
}
}
/**
* <p>
* 删除指定的key,也可以传入一个包含key的数组
* </p>
*
* @param keys 一个key 也可以使 string 数组
* @return 返回删除成功的个数
*/
public Long del(String... keys) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.del(keys);
} catch (Exception e) {
log.error(e.getMessage());
return 0L;
} finally {
returnResource(jedisPool, jedis);
}
}
/**
* <p>
* 删除指定的key,也可以传入一个包含key的数组
* </p>
* @param indexdb 选择redis库 0-15
* @param keys 一个key 也可以使 string 数组
* @return 返回删除成功的个数
*/
public Long del(int indexdb,String... keys) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.select(indexdb);
return jedis.del(keys);
} catch (Exception e) {
log.error(e.getMessage());
return 0L;
} finally {
returnResource(jedisPool, jedis);
}
}
/**
* <p>
* 删除指定的key,也可以传入一个包含key的数组
* </p>
* @param indexdb 选择redis库 0-15
* @param keys 一个key 也可以使 string 数组
* @return 返回删除成功的个数
*/
public Long del(int indexdb,byte[]... keys) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.select(indexdb);
return jedis.del(keys);
} catch (Exception e) {
log.error(e.getMessage());
return 0L;
} finally {
returnResource(jedisPool, jedis);
}
}
/**
* <p>
* 通过key向指定的value值追加值
* </p>
*
* @param key
* @param str
* @return 成功返回 添加后value的长度 失败 返回 添加的 value 的长度 异常返回0L
*/
public Long append(String key, String str) {
Jedis jedis = null;
Long res = null;
try {
jedis = jedisPool.getResource();
res = jedis.append(key, str);
} catch (Exception e) {
log.error(e.getMessage());
return 0L;
} finally {
returnResource(jedisPool, jedis);
}
return res;
}
/**
* <p>
* 判断key是否存在
* </p>
*
* @param key
* @return true OR false
*/
public Boolean exists(String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.exists(key);
} catch (Exception e) {
log.error(e.getMessage());
return false;
} finally {
returnResource(jedisPool, jedis);
}
}
/**
* <p>
* 清空当前数据库中的所有 key,此命令从不失败。
* </p>
*
* @return 总是返回 OK
*/
public String flushDB() {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.flushDB();
} catch (Exception e) {
log.error(e.getMessage());
} finally {
returnResource(jedisPool, jedis);
}
return null;
}
/**
* <p>
* 为给定 key 设置生存时间,当 key 过期时(生存时间为 0 ),它会被自动删除。
* </p>
*
* @param key
* @param value
* 过期时间,单位:秒
* @return 成功返回1 如果存在 和 发生异常 返回 0
*/
public Long expire(String key, int value, int indexdb) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.select(indexdb);
return jedis.expire(key, value);
} catch (Exception e) {
log.error(e.getMessage());
return 0L;
} finally {
returnResource(jedisPool, jedis);
}
}
/**
* <p>
* 以秒为单位,返回给定 key 的剩余生存时间
* </p>
*
* @param key
* @return 当 key 不存在时,返回 -2 。当 key 存在但没有设置剩余生存时间时,返回 -1 。否则,以秒为单位,返回 key
* 的剩余生存时间。 发生异常 返回 0
*/
public Long ttl(String key,int indexdb) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.select(indexdb);
return jedis.ttl(key);
}