在实际项目开发过程中,相信很多人都有用到过并且知道 redis 这个NoSQL,那如何将基于Jedis客户端的redis整合到spring-boot中呢?
maven依赖引用
<!-- Spring Boot Redis依赖 -->
<!-- 注意:1.5版本的依赖和2.0的依赖不一样,注意看哦 1.5我记得名字里面应该没有“data”,
2.0必须是“spring-boot-starter-data-redis” 这个才行-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<!-- 1.5的版本默认采用的连接池技术是jedis 2.0以上版本默认连接池是lettuce,
在这里采用jedis,所以需要排除lettuce的jar -->
<exclusions>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 添加jedis客户端 -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
我们要剔除掉spring-boot自带的客户端lettuce,并且引入jedis客户端。
配置yml环境参数
spring:
redis:
port: 6379
jedis:
pool:
max-active: 8
max-wait: -1
max-idle: 8
min-idle: 0
timeout: 60
password: hdl123456
host: 127.0.0.1
如上图所示分别配置redis缓存参数,具体解释会在配置类中说明。
redis配置类编写
@Configuration
public class RedisConfiguration {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.timeout}")
private int timeout;
@Value("${spring.redis.password}")
private String password;
@Value("${spring.redis.jedis.pool.max-active}")
private int maxActive;
@Value("${spring.redis.jedis.pool.max-wait}")
private int maxWait;
@Value("${spring.redis.jedis.pool.max-idle}")
private int maxIdle;
@Value("${spring.redis.jedis.pool.min-idle}")
private int minIdle;
@Bean
public JedisPoolConfig jedisPoolConfig() {
JedisPoolConfig config = new JedisPoolConfig();
/*最大空闲数*/
config.setMaxIdle(maxIdle);
/*连接池的最大数据库连接数*/
config.setMaxTotal(10000);
/*最大建立连接等待时间*/
config.setMaxWaitMillis(maxWait);
/*是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个*/
config.setTestOnBorrow(true);
/*在空闲时检查有效性, 默认false*/
config.setTestWhileIdle(false);
return config;
}
@Bean
public JedisPool jedisPool() {
JedisPool jedisPool;
if ("".equals(password)) {
jedisPool = new JedisPool(jedisPoolConfig(), host, port, timeout);
} else {
jedisPool = new JedisPool(jedisPoolConfig(), host, port, timeout, password);
}
RedisUtils.setJedisPool(jedisPool);
return jedisPool;
}
}
如上图根据参数构建JedisPool链接
编写RedisUtils工具类
/**
* @author: create by AdoreFT
* @version: v1.0
* @keyWord: Time is not waiting for me, you forgot to take me away.
* @description: RedisUtils
* @Date: 1/26/21 11:40 AM
**/
public class RedisUtils {
private static Logger logger = LoggerFactory.getLogger(RedisUtils.class);
/**
* SET IF NOT EXIST,即当key不存在时,我们进行set操作;若key已经存在,则不做任何操作;
*/
private static final String SET_IF_NOT_EXIST = "NX";
/**
* 要给这个key加一个过期的设置,具体时间由第五个参数决定
*/
private static final String SET_WITH_EXPIRE_TIME = "PX";
private static final String LOCK_SUCCESS = "OK";
private static JedisPool jedisPool;
public static void setJedisPool(JedisPool jedisPool) {
RedisUtils.jedisPool = jedisPool;
}
public static String redisGet(String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.get(key);
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
close(jedis);
}
return null;
}
public static void redisPut(String key, String val, int seconds) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.setex(key, seconds, val);
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
close(jedis);
}
}
public static boolean redisLock(String key, String value, int seconds) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
SetParams setParams = new SetParams();
setParams.nx();
setParams.px(seconds);
String result = jedis.set(key, value, setParams);
if (StringUtils.isNotBlank(result) && LOCK_SUCCESS.equals(result)) {
return true;
}
} catch (JedisConnectionException ex) {
logger.error(String.format("尝试加锁失败:%s", key));
return false;
} finally {
close(jedis);
}
return false;
}
/**
* 给指定key 设置过期时间
*
* @param key
* @param seconds
* @return
*/
public static Long expireTtl(String key, int seconds) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.expire(key, seconds);
} catch (JedisConnectionException ex) {
logger.error(String.format("expireTtl error %s", key), ex);
} finally {
close(jedis);
}
return 0L;
}
public static Long incrBy(String key, String val) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.incrBy(key, NumberUtil.toLong(val));
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
close(jedis);
}
return null;
}
public static void redisRelease(String catchKey) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.del(catchKey);
} catch (JedisConnectionException ex) {
logger.error(String.format("Release remove error %s", catchKey), ex);
} finally {
close(jedis);
}
}
private static void close(Jedis jedis) {
if (jedis != null) {
jedis.close();
}
}
}
这几步完成就可以使用redis了,后期会更新redis集群,redis哨兵模式,以及看门狗监听