StringRedis中怎么利用Template对Redis进行操作
发表于:2025-12-03 作者:千家信息网编辑
千家信息网最后更新 2025年12月03日,StringRedis中怎么利用Template对Redis进行操作,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。如何使用StringR
千家信息网最后更新 2025年12月03日StringRedis中怎么利用Template对Redis进行操作
StringRedis中怎么利用Template对Redis进行操作,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
如何使用StringRedisTemplate操作Redis详解
Redis简介
Redis 是一个开源(BSD许可)的,内存中的数据结构存储系统,它可以用作数据库、缓存和消息中间件。支持事务5.0版本新增stream数据类型。
Spring boot单数据源配置
Springboot的redis单数据源配置特别简单
(1)配置appliation.properties文件
spring.redis.host=x.x.x.xspring.redis.port=6379#redis的数据库号spring.redis.database=4spring.redis.timeout = 30000msspring.redis.jedis.pool.max-active=200spring.redis.jedis.pool.max-idle=0spring.redis.lettuce.pool.max-idle=5spring.redis.jedis.pool.max-wait=20000ms
(2)StringRedisTemplate的基本操作
StringRedisTemplate自动关闭redis连接//注入对象 @Autowiredprivate StringRedisTemplate stringRedisTemplate;#获取ValueOperations操作String数据ValueOperationsvalueOperations = stringRedisTemplate.opsForValue();valueOperations.set("strRedis","StringRedisTemplate");valueOperations.get("strRedis"); #设置过期时间 set("timeStep", new Date().getTime()+"", 2 ,TimeUnit.MINUTES);#获取SetOperations操作Set数据 SetOperations set = stringRedisTemplate.opsForSet(); set.add("set1","22"); set.add("set1","33"); set.add("set1","44"); Set resultSet =stringRedisTemplate.opsForSet().members("set1"); stringRedisTemplate.opsForSet().add("set2", "1","2","3");//向指定key中存放set集合 Set resultSet1 =stringRedisTemplate.opsForSet().members("set2"); log.info("resultSet:"+resultSet); log.info("resultSet1:"+resultSet1);#获取ListOperations操作List数据,list可以用来实现队列。 //将数据添加到key对应的现有数据的左边 Long redisList = stringRedisTemplate.opsForList().leftPush("redisList", "3"); stringRedisTemplate.opsForList().leftPush("redisList", "4"); //将数据添加到key对应的现有数据的右边 Long size = stringRedisTemplate.opsForList().size("redisList"); //从左往右遍历 String leftPop = stringRedisTemplate.opsForList().leftPop("redisList"); //从右往左遍历 String rightPop = stringRedisTemplate.opsForList().rightPop("redisList"); //查询全部元素 List range = stringRedisTemplate.opsForList().range("redisList", 0, -1); //查询前三个元素 List range1 = stringRedisTemplate.opsForList().range("redisList", 0, 3); //从左往右删除list中元素A (1:从左往右 -1:从右往左 0:删除全部) Long remove = stringRedisTemplate.opsForList().remove("key", 1, "A"); log.info("redisList----"+redisList); log.info("size----"+size); log.info("leftPop----"+leftPop); log.info("rightPop----"+rightPop); log.info("range----"+range); log.info("range1----"+range1); log.info("remove----"+remove); //判断key对应的map中是否存在hashBoolean aBoolean = stringRedisTemplate.opsForHash().hasKey("hash", "hash2");//往key对应的map中新增(key1,value1)stringRedisTemplate.opsForHash().put("hash", "hash2", "value1");//获取key对应的map中hash2的值Object o = stringRedisTemplate.opsForHash().get("hash", "hash2");//删除key对应的map中多个子hash(可变参数)Long delete = stringRedisTemplate.opsForHash().delete("hash", "key1", "key2", "key3");//获取hash对应的mapMap
Spring boot多数据源配置,配置一个1号库,一个4号库
添加依赖
org.apache.commons commons-pool2 org.springframework.boot spring-boot-starter-data-redis
修改application.properties配置文件
#1号库spring.redis.redis-onedb.database=0spring.redis.redis-onedb.hostName=192.168.90.42spring.redis.redis-onedb.port=9110spring.redis.redis-onedb.timeout=5000#4号库spring.redis.redis-fourdb.database=4spring.redis.redis-fourdb.hostName=192.168.90.42spring.redis.redis-fourdb.port=9110spring.redis.redis-fourdb.timeout=5000
创建RedisConfig.java文件
@Configurationpublic class RedisConfig {[@Bean](https://my.oschina.net/bean)@ConfigurationProperties(prefix = "spring.redis.lettuce.pool")@Scope(value = "prototype")public GenericObjectPoolConfig redisPool(){ return new GenericObjectPoolConfig();}@Bean@ConfigurationProperties(prefix = "spring.redis.redis-fourdb")public RedisStandaloneConfiguration redisConfigA(){ return new RedisStandaloneConfiguration();}@Bean@ConfigurationProperties(prefix = "spring.redis.redis-onedb")public RedisStandaloneConfiguration redisConfigB(){ return new RedisStandaloneConfiguration();}@Primary@Beanpublic LettuceConnectionFactory factoryA(GenericObjectPoolConfig config, RedisStandaloneConfiguration redisConfigA){ LettuceClientConfiguration clientConfiguration = LettucePoolingClientConfiguration.builder() .poolConfig(config).commandTimeout(Duration.ofMillis(config.getMaxWaitMillis())).build(); return new LettuceConnectionFactory(redisConfigA, clientConfiguration);}@Beanpublic LettuceConnectionFactory factoryB(GenericObjectPoolConfig config, RedisStandaloneConfiguration redisConfigB){ LettuceClientConfiguration clientConfiguration = LettucePoolingClientConfiguration.builder() .poolConfig(config).commandTimeout(Duration.ofMillis(config.getMaxWaitMillis())).build(); return new LettuceConnectionFactory(redisConfigB, clientConfiguration);}@Bean(name = "fourRedis")public StringRedisTemplate redisBusTemplate(@Qualifier("factoryA") LettuceConnectionFactory factoryA){ StringRedisTemplate template = getRedisTemplate(); template.setConnectionFactory(factoryA); return template;}@Bean(name = "oneRedis")public StringRedisTemplate redisLoginTemplate(@Qualifier("factoryB")LettuceConnectionFactory factoryB){ StringRedisTemplate template = getRedisTemplate(); template.setConnectionFactory(factoryB); return template;}private StringRedisTemplate getRedisTemplate(){ StringRedisTemplate template = new StringRedisTemplate(); template.setValueSerializer(new GenericFastJsonRedisSerializer()); template.setValueSerializer(new StringRedisSerializer()); return template;}}在需要使用的类,注入就可以使用
@Resource(name = "oneRedis")private StringRedisTemplate oneRedis;@Resource(name = "fourRedis")private StringRedisTemplate fourRedis;
StringRedisTemplate实现事务
stringRedisTemplate.setEnableTransactionSupport(true); try { stringRedisTemplate.multi();//开启事务 stringRedisTemplate.opsForValue().increment("count", 1); stringRedisTemplate.opsForValue().increment("count1", 2); //提交 stringRedisTemplate.exec(); }catch (Exception e){ log.error(e.getMessage(), e); //开启回滚 stringRedisTemplate.discard(); }**注意:**StringRedisTemplate开启事务之后,不释放连接。如果我们使用Spring事务管理不存在这个问题
StringRedisTemplate实现乐观锁
redisTemplate.watch("key"); // 1redisTemplate.multi();redisTemplate.boundValueOps("key").set(""+id);List list= redisTemplate.exec();System.out.println(list);if(list != null ){ //操作成功 System.out.println(id+"操作成功");}else{ //操作失败 System.out.println(id+"操作失败");} StringRedisTemplate实现pipe管道
StringRedisTemplate实现分布式锁
String lockKey = "key";String lockValue = lockKey+System.currentTimeMillis();// value需要记住用于解锁while (true){ Boolean ifPresent = stringRedisTemplate.opsForValue(). setIfAbsent("redis-lock:" + lockKey, lockValue, 3, TimeUnit.SECONDS); if (ifPresent){ log.info("get redis-lock success"); break; } }//解锁 String lockKey = "key"; String lockValue = lockKey + System.currentTimeMillis(); boolean result = false; // value需要记住用于解锁 stringRedisTemplate.watch("redis-lock:" + lockKey); String value = stringRedisTemplate.opsForValue().get("redis-lock:" + lockKey); if (null == value){ result = true; }else if (value.equals(lockValue)) { stringRedisTemplate.delete("redis-lock:" + lockKey); result = true; } stringRedisTemplate.unwatch();Redis缓存击穿、穿透和雪崩
缓存击穿,是指一个key非常热点,在不停的扛着大并发,大并发集中对这一个点进行访问,当这个key在失效的瞬间,持续的大并发就穿破缓存,直接请求数据库,就像在一个屏障上凿开了一个洞 缓存穿透,是指查询一个数据库一定不存在的数据。正常的使用缓存流程大致是,数据查询先进行缓存查询,如果key不存在或者key已经过期,再对数据库进行查询,并把查询到的对象,放进缓存。如果数据库查询对象为空,则不放进缓存。解决办法是即使查出的对象为空,也放入缓存时间设短一点。缓存雪崩,是指在某一个时间段,缓存集中过期失效。
看完上述内容,你们掌握StringRedis中怎么利用Template对Redis进行操作的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注行业资讯频道,感谢各位的阅读!
数据
缓存
查询
数据库
配置
事务
对象
时间
元素
数据源
文件
问题
成功
内容
方法
更多
雪崩
放进
穿透
乐观
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
数据库同步双写和异步双写
数据库删除重复记录
有关网络安全心得体会
软件开发需要购买什么软件
大连天健棋牌连接服务器失败
网络安全常见威胁的特征
win10服务器界面
淮北保险软件开发费用
金融行业网络安全保障总体框架
怎样筛选好的软件开发公司
英雄联盟出装收益数据库
公司网络安全发文
手机软件开发平台搭建
最大的文本数据库是什么
数据库技术难度
做软件开发应该选什么专业
2017网络安全厂商排行
sybase查看数据库下的表
浏览器可直接访问数据库吗
无线传感器网络技术的优点
派派怎么改服务器
网络安全主体责任法律依据
白城app软件开发
为什么学校近期要强调网络安全
update不更新数据库
启动服务器.bat
政府人员网络技术
数据库类型是否
硒都梵泊互联网科技有限公司
网络安全模式下装