Springboot使用Jedis
1、导包
org.springframework.boot
spring-boot-starter-data-redis
redis.clients
jedis
3.1.0
org.projectlombok
lombok
1.18.8
provided
2、添加 application.properties 配置
# Redis服务器地址
redis.host=127.0.0.1
# Redis服务器连接端口
redis.port=6379
# Redis服务器连接密码(默认为空)
redis.password=null
redis.timeout=30000
# 连接池最大连接数(使用负值表示没有限制)
redis.maxTotal=30
# 连接池中的最大空闲连接
redis.maxIdle=10
redis.numTestsPerEvictionRun=1024
redis.timeBetweenEvictionRunsMillis=30000
redis.minEvictableIdleTimeMillis=1800000
redis.softMinEvictableIdleTimeMillis=10000
# 连接池最大阻塞等待时间(使用负值表示没有限制)
redis.maxWaitMillis=1500
redis.testOnBorrow=true
redis.testWhileIdle=true
redis.blockWhenExhausted=false
redis.JmxEnabled=true
3、编写 RedisConfig 配置文件
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;
@Configuration
@PropertySource("classpath:application.properties")
public class RedisConfig {
@Value("${redis.host}")
private String host;
@Value("${redis.port}")
private int port;
@Value("${redis.timeout}")
private int timeout;
@Value("${redis.maxIdle}")
private int maxIdle;
@Value("${redis.maxWaitMillis}")
private int maxWaitMillis;
@Value("${redis.blockWhenExhausted}")
private Boolean blockWhenExhausted;
@Value("${redis.JmxEnabled}")
private Boolean JmxEnabled;
@Bean
public JedisPool jedisPoolFactory() {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxIdle(maxIdle);
jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
// 连接耗尽时是否阻塞, false报异常,true阻塞直到超时, 默认true
jedisPoolConfig.setBlockWhenExhausted(blockWhenExhausted);
// 是否启用pool的jmx管理功能, 默认true
jedisPoolConfig.setJmxEnabled(JmxEnabled);
JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout);
return jedisPool;
}
}
4、编写RedisUtil工具类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.params.SetParams;
@Component
public class RedisUtil {
@Autowired
private JedisPool jedisPool;
/**
* 向Redis中存值,永久有效
*/
public String set(String key, String value) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.set(key, value);
} catch (Exception e) {
return "0";
} finally {
jedis.close();
}
}
/**
* 根据传入Key获取指定Value
*/
public String get(String key) {
Jedis jedis = null;
String value;
try {
jedis = jedisPool.getResource();
value = jedis.get(key);
} catch (Exception e) {
return "0";
} finally {
jedis.close();
}
return value;
}
/**
* 校验Key值是否存在
*/
public Boolean exists(String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.exists(key);
} catch (Exception e) {
return false;
} finally {
jedis.close();
}
}
/**
* 删除指定Key-Value
*/
public Long del(String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.del(key);
} catch (Exception e) {
return 0L;
} finally {
jedis.close();
}
}
/**
* 分布式锁
* @param key
* @param value
* @param time 锁的超时时间,单位:秒
*
* @return 获取锁成功返回"OK",失败返回null
*/
public String getDistributedLock(String key,String value,int time){
Jedis jedis = null;
String ret = "";
try {
jedis = jedisPool.getResource();
ret = jedis.set(key, value, new SetParams().nx().ex(time));
return ret;
} catch (Exception e) {
return null;
} finally {
jedis.close();
}
}
}
5、使用 springboot 默认 RedisTemplate
- 导包
org.springframework.boot
spring-boot-starter-data-redis
- 配置 application.properties
spring:
redis:
host: 192.168.1.111
port: 6379
由于Springboot-data-redis帮我们自动装载了RedisTemplate对象,所以我们无需注册该bean。但是,如果用默认的 RedisTemplate ,那么在序列化存到redis中就会发现,key 就变的“不正常”了。
比如,存之前key为"test" ,进入redis看,key就变成了"\xac\xed\x00\x05t\x00\x04test" 。这与RedisTemplate默认提供的序列化协议有关。为了使其更符合我们的需求,我们需要订制序列化协议。
- 选择Springboot自带的Jackson为序列化协议,进行配置
@Configuration
public class RedisConfiguration {
@Bean
public RedisTemplate
- 测试使用
@RunWith(SpringRunner.class)
@SpringBootTest(classes = EdApplication.class)
public class FenCiUtilText {
@Autowired
private RedisTemplate redisTemplate;
//测试放入
@Test
public void testRedisSet() {
try {
redisTemplate.opsForValue().set("test","This is a Springboot-Redis test!");
} catch (Exception e){
System.out.println(e.toString());
}
}
//测试拿出
@Test
public void testRedisGet() {
try {
String key="test";
Boolean isHas = redisTemplate.hasKey(key);
if (isHas){
Object test = redisTemplate.opsForValue().get(key);
System.out.println(test);
}else {
System.out.println("抱歉!不存在key值为"+key);
}
} catch (Exception e){
System.out.println(e.toString());
}
}
}
参考链接: