本文介绍了springboot集成redis需要的一些配置以及常见的redis操作工具类。
提示:以下是本篇文章正文内容,下面案例可供参考
一、redis是什么?redis是一个高性能、基于内存级别读写的非关系型数据库
二、使用步骤 引入库定义配置类 数据序列化以及反序列化org.springframework.boot spring-boot-starter-data-redis cn.hutool hutool-all org.apache.commons commons-pool2 com.alibaba fastjson
public class FastJsonRedisSerializer属性配置implements RedisSerializer { private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); private Class clazz; public FastJsonRedisSerializer(Class clazz) { super(); this.clazz = clazz; } @Override public byte[] serialize(T t) throws SerializationException { if (null == t) { return new byte[0]; } return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET); } @Override public T deserialize(byte[] bytes) throws SerializationException { if (null == bytes || bytes.length <= 0) { return null; } String str = new String(bytes, DEFAULT_CHARSET); //禁用关键字检测 return JSON.parseObject(str, clazz, Feature.DisableSpecialKeyDetect); } }
@Data
@ConfigurationProperties(
prefix = "spring.myredis"
)
@Component(value = "MyRedisProperties")
public class MyRedisProperties{
private Integer backupdb;
private int database = 0;
private String url;
private String host = "localhost";
private String username;
private String password;
private int port = 6379;
private boolean ssl;
private Duration timeout;
private Duration connectTimeout;
}
主从库配置
@Configuration
@EnableConfigurationProperties
@EnableCaching
public class RedisConfig {
@Resource
MyRedisProperties myRedisProperties;
@Bean
@Primary
public RedisTemplate redisTemplateMaster(RedisConnectionFactory redisConnectionFactory){
// 创建redis序列化器
RedisTemplate redisTemplate = new RedisTemplate<>();
FastJsonRedisSerializer
常用操作工具类
public class RedisUtils {
public RedisTemplate redisTemplate;
public RedisUtils(Boolean isMaster) {
if (isMaster) {
redisTemplate = SpringUtil.getBean("redisTemplateMaster");
return;
}
redisTemplate = SpringUtil.getBean("redisTemplateSlave");
}
public void setObject(final String key, final Object value) {
redisTemplate.opsForValue().set(key, value);
}
public void setObject(final String key, final Object value, final Long timeout, final TimeUnit timeUnit) {
redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
}
public boolean expire(final String key, final long timeout) {
return expire(key, timeout, TimeUnit.SECONDS);
}
public boolean expire(final String key, final long timeout, final TimeUnit unit) {
return redisTemplate.expire(key, timeout, unit);
}
public Object getObject(final String key) {
return redisTemplate.opsForValue().get(key);
}
public T getObject(final String key,final Class clazz) {
return JSONUtil.toBean(JSONUtil.toJsonStr(redisTemplate.opsForValue().get(key)),clazz);
}
public boolean deleteObject(final String key) {
return redisTemplate.delete(key);
}
public long deleteObject(final Collection collection) {
return redisTemplate.delete(collection);
}
public long setList(final String key, final Collection dataList) {
Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
return count == null ? 0 : count;
}
public List getList(final String key) {
return redisTemplate.opsForList().range(key, 0, -1);
}
public List getList(final String key,final Class clazz) {
return JSONUtil.toList(JSONUtil.toJsonStr(redisTemplate.opsForList().range(key, 0, -1)),clazz);
}
public void setSet(final String key, final Set dataSet) {
redisTemplate.opsForSet().add(key, dataSet);
}
public Set getSet(final String key) {
return redisTemplate.opsForSet().members(key);
}
public void setMap(final String key, final Map dataMap) {
if (dataMap != null) {
redisTemplate.opsForHash().putAll(key, dataMap);
}
}
public Map getMap(final String key) {
return redisTemplate.opsForHash().entries(key);
}
public void setMap(final String key, final String hKey, final Object value) {
redisTemplate.opsForHash().put(key, hKey, value);
}
public Object getMap(final String key, final String hKey) {
return redisTemplate.opsForHash().get(key, hKey);
}
public List getMap(final String key, final Collection hKeys) {
return redisTemplate.opsForHash().multiGet(key, hKeys);
}
public Collection keys(final String pattern) {
return redisTemplate.keys(pattern);
}
}
启动配置application.yml
spring:
myredis:
database: 0
backupdb: 1
host: localhost
port: 6379
timeout: 30
运行启动类
@SpringBootTest(classes = SpringBootExampleApplication.class)
@Slf4j
@RunWith(SpringRunner.class)
public class RedisTest {
@Test
public void testRedis(){
String STRING_KEY = "testString";
String LIST_KEY = "testList";
String HASH_KEY = "testHash";
String SET_KEY = "testSet";
RedisUtils redisUtils = new RedisUtils(true);
RedisUtils redisUtilSalve = new RedisUtils(false);
// string操作
redisUtils.setObject(STRING_KEY,"test");
redisUtilSalve.setObject(STRING_KEY,new Student(20,"小明"));
// list操作
redisUtils.setList(LIST_KEY, Arrays.asList(1,2));
redisUtilSalve.setList(LIST_KEY,Arrays.asList(new Student(1,"1"),new Student(2,"2")));
// map操作
redisUtils.setMap(HASH_KEY, MapUtil.of(HASH_KEY,"test"));
redisUtilSalve.setMap(HASH_KEY,MapUtil.of(HASH_KEY,"testSlave"));
// set 操作
HashSet hashSet = new HashSet();
hashSet.add("test");
hashSet.add("test1");
redisUtils.setSet(SET_KEY,hashSet);
hashSet.add("testSalve");
redisUtilSalve.setSet(SET_KEY,hashSet);
// 打印展示
// string打印
System.out.println(redisUtils.getObject(STRING_KEY));
Student student = redisUtilSalve.getObject(STRING_KEY, Student.class);
System.out.println(student);
// list 打印
System.out.println(redisUtils.getList(LIST_KEY));
List studentList = redisUtilSalve.getList(LIST_KEY,Student.class);
studentList.stream().forEach(System.out::println);
// map 打印
redisUtils.getMap(HASH_KEY).forEach((k,v)->{
System.out.println(k+":"+v);
});
redisUtilSalve.getMap(HASH_KEY).forEach((k,v)->{
System.out.println(k+":"+v);
});
// set 打印
redisUtils.getSet(SET_KEY).forEach(v->{
System.out.println(v);
});
redisUtilSalve.getSet(SET_KEY).forEach(v->{
System.out.println(v);
});
}
}
打印效果
=======string打印====== test Student(age=20, name=小明) =======list打印====== [1, 2] Student(age=1, name=1) Student(age=2, name=2) =======map打印====== testHash:test testHash:testSlave =======set打印====== [test, test1] [test, testSalve, test1]Another Redis Desktop Manager 工具效果
以上就是介绍的全部内容,把一些常用便捷的方法封装进去,方便后续二次开发引用。
源码地址测试代码地址在:https://gitee.com/teajoy/springboot-modules/tree/master/springboot-example
https://gitee.com/teajoy/springboot-modules/tree/master/springboot-redis



