java操作redis库,开箱即用

application.yml

spring:application:name: demo#Redis相关配置redis:data:# 地址host: localhost# 端口,默认为6379port: 6379# 数据库索引database: 0# 密码password:# 连接超时时间timeout: 10slettuce:pool:# 连接池中的最小空闲连接min-idle: 0# 连接池中的最大空闲连接max-idle: 8# 连接池的最大数据库连接数max-active: 8# #连接池最大阻塞等待时间(使用负值表示没有限制)max-wait: -1ms

依赖

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>

序列化配置

package com.example.demo.config;import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;@Configuration
public class RedisConfig {//编写我们自己的配置redisTemplate@Bean@SuppressWarnings("all")public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {RedisTemplate<String, Object> template = new RedisTemplate<>();template.setConnectionFactory(redisConnectionFactory);// JSON序列化配置Jackson2JsonRedisSerializer jsonRedisSerializer=new Jackson2JsonRedisSerializer(Object.class);ObjectMapper objectMapper=new ObjectMapper();objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);jsonRedisSerializer.setObjectMapper(objectMapper);// String的序列化StringRedisSerializer stringRedisSerializer=new StringRedisSerializer();//key和hash的key都采用String的序列化方式template.setKeySerializer(stringRedisSerializer);template.setHashKeySerializer(stringRedisSerializer);//value和hash的value都采用jackson的序列化方式template.setValueSerializer(jsonRedisSerializer);template.setHashValueSerializer(jsonRedisSerializer);template.afterPropertiesSet();return template;}
}

工具类

package com.example.demo.utils;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;import java.util.*;
import java.util.concurrent.TimeUnit;/*** spring redis 工具类** @author ruoyi**/
@SuppressWarnings(value = { "unchecked", "rawtypes" })
@Component
public class RedisCache
{@Autowiredpublic RedisTemplate redisTemplate;/*** 缓存基本的对象,Integer、String、实体类等** @param key 缓存的键值* @param value 缓存的值*/public <T> void setCacheObject(final String key, final T value){redisTemplate.opsForValue().set(key, value);}/*** 缓存基本的对象,Integer、String、实体类等** @param key 缓存的键值* @param value 缓存的值* @param timeout 时间* @param timeUnit 时间颗粒度*/public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit){redisTemplate.opsForValue().set(key, value, timeout, timeUnit);}/*** 设置有效时间** @param key Redis键* @param timeout 超时时间* @return true=设置成功;false=设置失败*/public boolean expire(final String key, final long timeout){return expire(key, timeout, TimeUnit.SECONDS);}/*** 设置有效时间** @param key Redis键* @param timeout 超时时间* @param unit 时间单位* @return true=设置成功;false=设置失败*/public boolean expire(final String key, final long timeout, final TimeUnit unit){return redisTemplate.expire(key, timeout, unit);}/*** 获取有效时间** @param key Redis键* @return 有效时间*/public long getExpire(final String key){return redisTemplate.getExpire(key);}/*** 判断 key是否存在** @param key 键* @return true 存在 false不存在*/public Boolean hasKey(String key){return redisTemplate.hasKey(key);}/*** 获得缓存的基本对象。** @param key 缓存键值* @return 缓存键值对应的数据*/public <T> T getCacheObject(final String key){ValueOperations<String, T> operation = redisTemplate.opsForValue();return operation.get(key);}/*** 删除单个对象** @param key*/public boolean deleteObject(final String key){return redisTemplate.delete(key);}/*** 删除集合对象** @param collection 多个对象* @return*/public boolean deleteObject(final Collection collection){return redisTemplate.delete(collection) > 0;}/*** 缓存List数据** @param key 缓存的键值* @param dataList 待缓存的List数据* @return 缓存的对象*/public <T> long setCacheList(final String key, final List<T> dataList){Long count = redisTemplate.opsForList().rightPushAll(key, dataList);return count == null ? 0 : count;}/*** 获得缓存的list对象** @param key 缓存的键值* @return 缓存键值对应的数据*/public <T> List<T> getCacheList(final String key){return redisTemplate.opsForList().range(key, 0, -1);}/*** 缓存Set** @param key 缓存键值* @param dataSet 缓存的数据* @return 缓存数据的对象*/public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet){BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);Iterator<T> it = dataSet.iterator();while (it.hasNext()){setOperation.add(it.next());}return setOperation;}/*** 获得缓存的set** @param key* @return*/public <T> Set<T> getCacheSet(final String key){return redisTemplate.opsForSet().members(key);}/*** 缓存Map** @param key* @param dataMap*/public <T> void setCacheMap(final String key, final Map<String, T> dataMap){if (dataMap != null) {redisTemplate.opsForHash().putAll(key, dataMap);}}/*** 获得缓存的Map** @param key* @return*/public <T> Map<String, T> getCacheMap(final String key){return redisTemplate.opsForHash().entries(key);}/*** 往Hash中存入数据** @param key Redis键* @param hKey Hash键* @param value 值*/public <T> void setCacheMapValue(final String key, final String hKey, final T value){redisTemplate.opsForHash().put(key, hKey, value);}/*** 获取Hash中的数据** @param key Redis键* @param hKey Hash键* @return Hash中的对象*/public <T> T getCacheMapValue(final String key, final String hKey){HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();return opsForHash.get(key, hKey);}/*** 获取多个Hash中的数据** @param key Redis键* @param hKeys Hash键集合* @return Hash对象集合*/public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys){return redisTemplate.opsForHash().multiGet(key, hKeys);}/*** 删除Hash中的某条数据** @param key Redis键* @param hKey Hash键* @return 是否成功*/public boolean deleteCacheMapValue(final String key, final String hKey){return redisTemplate.opsForHash().delete(key, hKey) > 0;}/*** 获得缓存的基本对象列表** @param pattern 字符串前缀* @return 对象列表*/public Collection<String> keys(final String pattern){return redisTemplate.keys(pattern);}
}

测试类

RedisCache

package com.example.demo.test;import com.example.demo.utils.RedisCache;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.*;import java.util.*;
import java.util.concurrent.TimeUnit;@SpringBootTest
class RedisCacheTest {@AutowiredRedisCache redisCache;@AutowiredRedisTemplate redisTemplate;private static final String TEST_KEY = "test:list:key";// 1.缓存对象@Testpublic void setObject() {// redisCache.setCacheObject("object","test");// 附带过期时间redisCache.setCacheObject("object", "test", 10, TimeUnit.SECONDS);}// 2.过期时间@Testpublic void setTimeOut() {redisCache.setCacheObject("object", "test");// 更新过期时间redisCache.expire("object", 100, TimeUnit.SECONDS);// 获取过期时间System.out.println(redisCache.getExpire("object"));;}// 3.判断key是否存在@Testpublic void check() {System.out.println(redisCache.hasKey("object"));}// 4.获取对象@Testpublic void getObject() {System.out.println((String) redisCache.getCacheObject("object"));}// 5.删除对象/如果传递集合就是删除多个key@Testpublic void deleteObject() {redisCache.setCacheObject("obj", "1");System.out.println((String) redisCache.getCacheObject("obj"));redisCache.deleteObject("obj");System.out.println((String) redisCache.getCacheObject("obj"));}// 6.获取list对象@Testpublic void getList() {// 1. 准备测试数据List<String> testData = Arrays.asList("item1", "item2", "item3");redisCache.setCacheList(TEST_KEY, testData);// 2. 调用获取方法List<Object> result = redisCache.getCacheList(TEST_KEY);// 3. 验证结果for (Object o : result) {System.out.println(o);}}// 7.获取set对象@Testpublic void getSet() {// 1. 准备测试数据Set<String> set = Set.of("a", "b");redisCache.setCacheSet("TestSet", set);// 2. 调用获取方法Set<Object> cacheSet = redisCache.getCacheSet("TestSet");// 3. 验证结果for (Object o : cacheSet) {System.out.println(o);}}// 8.Map@Testpublic void getMap() {// 1. 准备测试数据Map<String, String> stringStringMap = new HashMap<>();stringStringMap.put("name","zww");stringStringMap.put("age","21");redisCache.setCacheMap("TestMap", stringStringMap);// 2. 调用获取方法Map<String, Object> testMap = redisCache.getCacheMap("TestMap");// 3. 验证结果System.out.println(testMap.get("name"));System.out.println(testMap.get("age"));}// 9.hash数据 对比map多了一个外层key@Testpublic void getHash() {// 1. 准备测试数据redisCache.setCacheMapValue("hashMap","testHashMap","1");redisCache.setCacheMapValue("hashMap","testHashMap2","2");// 2. 调用获取方法System.out.println((String) redisCache.getCacheMapValue("hashMap","testHashMap"));System.out.println((String) redisCache.getCacheMapValue("hashMap","testHashMap2"));}}

RedisTemplate

package com.example.demo.test;import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.core.*;import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;@SpringBootTest
public class RedisTemplateTest {@AutowiredRedisTemplate redisTemplate;/*** 操作String类型的数据*/@Testvoid contextLoads() {// redisTemplate.opsForValue().set("mannor" ,"rediaz");String mannor = (String) redisTemplate.opsForValue().get("mannor");System.out.println(mannor);redisTemplate.opsForValue().set("k1", "v1", 10L, TimeUnit.SECONDS);Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent("mannor1", "mannor");System.out.println(aBoolean);}/*** 操作hash类型的数据*/@Testpublic void hashTest() {HashOperations hashOperations = redisTemplate.opsForHash();// 存hashOperations.put("002", "name", "zhangsan");hashOperations.put("002", "age", "20");hashOperations.put("002", "addr", "beijing");// 取Object age = hashOperations.get("002", "age");
//        System.out.println((String) age);// 获取所有字段Set keys = hashOperations.keys("002");for (Object key : keys) {
//            System.out.println(key);}// 获得hash结构中的所有值List values = hashOperations.values("002");for (Object value : values) {System.out.println(value);}}/*** 操作list类型的数据*/@Testpublic void listTest() {ListOperations listOperations = redisTemplate.opsForList();// 存listOperations.leftPush("list", "00");listOperations.leftPushAll("list", "01", "02", "03");// 取值List list = listOperations.range("list", 0, -1);for (Object val : list) {System.out.println(val);}System.out.println("------------------------------------------------------------");// 获取长度来遍历Long size = listOperations.size("list");for (int i = 0; i < size; i++) {// 出队列String element = (String) listOperations.rightPop("list");System.out.println(element);}}/*** 操作Set类型的数据*/@Testpublic void testSet() {SetOperations setOperations = redisTemplate.opsForSet();// 存值setOperations.add("myset", "a", "b", "c", "a");// 取值Set<String> myset = setOperations.members("myset");for (String o : myset) {System.out.println(o);}// 删除成员setOperations.remove("myset", "a", "b");// 取值myset = setOperations.members("myset");for (String o : myset) {System.out.println(o);}}@Testpublic void testZset() {ZSetOperations zSetOperations = redisTemplate.opsForZSet();// 存值zSetOperations.add("myZset", "a", 10.0);zSetOperations.add("myZset", "b", 11.0);zSetOperations.add("myZset", "c", 12.0);zSetOperations.add("myZset", "a", 13.0);// 取值Set<String> myZset = zSetOperations.range("myZset", 0, -1);for (String s : myZset) {System.out.println(s);}// 修改分数zSetOperations.incrementScore("myZset", "b", 20.0);// 取值myZset = zSetOperations.range("myZset", 0, -1);for (String s : myZset) {System.out.println(s);}// 删除成员zSetOperations.remove("myZset", "a", "b");// 取值myZset = zSetOperations.range("myZset", 0, -1);for (String s : myZset) {System.out.println(s);}}/*** 通用操作,针对不同的数据类型都可以操作*/@Testpublic void testCommon() {// 获取Redis中所有的keySet<String> keys = redisTemplate.keys("*");for (String key : keys) {System.out.println(key);}// 判断某个key是否存在Boolean itcast = redisTemplate.hasKey("itcast");System.out.println(itcast);// 删除指定keyredisTemplate.delete("myZset");// 获取指定key对应的value的数据类型DataType dataType = redisTemplate.type("myset");System.out.println(dataType.name());}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/901432.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Cribl 通过Splunk search collector 来收集数据

今天利用Spliunk search collector 来收集数据啦:还是要先cribl 的官方文档: Splunk Search Collector | Cribl Docs Splunk Search Collector Cribl Stream supports collecting search results from Splunk queries. The queries can be both simple and complex, as well a…

What Was the “Game Genie“ Cheat Device, and How Did It Work?

什么是“Game Genie”作弊装置&#xff0c;它是如何工作的&#xff1f; First released in 1991, the Game Genie let players enter special codes that made video games easier or unlocked other functions. Nintendo didnt like it, but many gamers loved it. Heres wha…

位运算题目:连接连续二进制数字

文章目录 题目标题和出处难度题目描述要求示例数据范围 解法思路和算法代码复杂度分析 题目 标题和出处 标题&#xff1a;连接连续二进制数字 出处&#xff1a;1680. 连接连续二进制数字 难度 5 级 题目描述 要求 给定一个整数 n \texttt{n} n&#xff0c;将 1 \text…

第十六届蓝桥杯Java b组(试题C:电池分组)

问题描述&#xff1a; 输入格式&#xff1a; 输出格式&#xff1a; 样例输入&#xff1a; 2 3 1 2 3 4 1 2 3 4 样例输出: YES NO 说明/提示 评测用例规模与约定 对于 30% 的评测用例&#xff0c;1≤T≤10&#xff0c;2≤N≤100&#xff0c;1≤Ai​≤10^3。对于 100…

63. 评论日记

2025年4月14日18:53:30 雷军这次是真的累了_哔哩哔哩_bilibili

电商中的订单支付(内网穿透)

支付页面 接口文档 Operation(summary"获取订单信息") GetMapping("auth/{orderId}") public Reuslt<OrderInfo> getOrderInfo(Parameter(name"orderId",description"订单id",requiredtrue) PathVaariable Long orderId){OrderI…

MySQL表的使用(4)

首先回顾一下之前所学的增删查改&#xff0c;这些覆盖了平时使用的80% 我们上节课中学习到了MySQL的约束 其中Primary key 是主键约束&#xff0c;我们今天要学习的是外键约束 插入一个表 外键约束 父表 子表 这条记录中classid为5时候&#xff0c;不能插入&#xff1b; 删除…

Kotlin作用域函数

在 Kotlin 中&#xff0c;.apply 是一个 作用域函数&#xff08;Scope Function&#xff09;&#xff0c;它允许你在一个对象的上下文中执行代码块&#xff0c;并返回该对象本身。它的设计目的是为了 对象初始化 或 链式调用 时保持代码的简洁性和可读性。 // 不使用 apply va…

C#集合List<T>与HashSet<T>的区别

在C#中&#xff0c;List和HashSet都是用于存储元素的集合&#xff0c;但它们在内部实现、用途、性能特性以及使用场景上存在一些关键区别。 内部实现 List&#xff1a;基于数组实现的&#xff0c;可以包含重复的元素&#xff0c;并且元素是按照添加的顺序存储的。 HashSet&…

Python 实现的运筹优化系统数学建模详解(最大最小化模型)

一、引言 在数学建模的实际应用里&#xff0c;最大最小化模型是一种极为关键的优化模型。它的核心目标是找出一组决策变量&#xff0c;让多个目标函数值里的最大值尽可能小。该模型在诸多领域&#xff0c;如资源分配、选址规划等&#xff0c;都有广泛的应用。本文将深入剖析最大…

数据库的种类及常见类型

一&#xff0c;数据库的种类 最常见的数据库类型分为两种&#xff0c;关系型数据库和非关系型数据库。 二&#xff0c;关系型数据库介绍 生产环境主流的关系型数据库有 Oracle、SQL Server、MySQL/MariaDB等。 关系型数据库在存储数据时实际就是采用的一张二维表&#xff0…

PE文件(十五)绑定导入表

我们在分析Windows自带的一些程序时&#xff0c;常常发现有的程序&#xff0c;如notepad&#xff0c;他的IAT表在文件加载内存前已经完成绑定&#xff0c;存储了函数的地址。这样做可以使得程序是无需修改IAT表而直接启动&#xff0c;这时程序启动速度变快。但这种方式只适用于…

计算机网络分层模型:架构与原理

前言 计算机网络通过不同的层次结构来实现通信和数据传输&#xff0c;这种分层设计不仅使得网络更加模块化和灵活&#xff0c;也使得不同类型的通信能够顺利进行。在网络协议和通信体系中&#xff0c;最广为人知的分层模型有 OSI模型 和 TCP/IP模型。这两种模型分别定义了计算…

Ollama模型显存管理机制解析与Flask部署方案对比

一、Ollama显存释放机制 Ollama部署模型后&#xff0c;显存占用分为两种情况&#xff1a; 首次调用后短暂闲置&#xff08;约5分钟内&#xff09;&#xff1a; • 释放KV Cache等中间计算数据&#xff08;约回收30%-50%显存&#xff09;。 • 模型权重仍保留在显存中&#xf…

KWDB创作者计划—KWDB技术重构:重新定义数据与知识的神经符号革命

引言&#xff1a;数据洪流中的范式危机 在AI算力突破千卡集群、大模型参数量级迈向万亿的时代&#xff0c;传统数据库系统正面临前所未有的范式危机。当GPT-4展现出跨领域推理能力&#xff0c;AlphaFold3突破蛋白质预测精度时&#xff0c;数据存储系统却仍在沿用基于关系代数的…

Unified Modeling Language,统一建模语言

UML&#xff08;Unified Modeling Language&#xff0c;统一建模语言&#xff09;是一种标准化的图形化建模语言&#xff0c;用于可视化、规范和文档化软件系统的设计。UML 提供了一套通用的符号和规则&#xff0c;帮助开发者、架构师和团队成员更好地理解和沟通软件系统的结构…

IO模式精讲总结

一、IO模型概述 Java中的IO模型主要分为BIO&#xff08;同步阻塞IO&#xff09;、NIO&#xff08;同步非阻塞IO&#xff09;和AIO&#xff08;异步非阻塞IO&#xff09;三种。它们分别适用于不同的业务场景&#xff0c;理解其核心机制对高性能网络编程至关重要。 二、BIO&…

使用pybind11开发c++扩展模块输出到控制台的中文信息显示乱码的问题

使用pybind11开发供Python项目使用的C++扩展模块时,如果在扩展模块的C++代码中向控制台输出的信息中包含中文,python程序的控制台很容易出现乱码。以如下C++扩展框架代码为例(这是对上一篇文章简明使用pybind11开发pythonc+扩展模块教程-CSDN博客中的C++扩展框架代码进行少量…

通过jstack分析线程死锁场景

死锁的四个必要条件&#xff1a;互斥、持有并等待、不可抢占、循环等待。 死锁场景是两个线程各自持有某个锁&#xff0c;并试图获取对方持有的锁&#xff0c;导致互相等待。 创建死锁示例代码 package io.renren.controller;import org.springframework.web.bind.annotation…

PyTorch梯度:深度学习的引擎与实战解析

一、梯度&#xff1a;深度学习中的指南针 1.1 什么是梯度&#xff1f; 梯度是函数在某一点变化率最大的方向及其大小&#xff0c;就像爬山时最陡峭的上坡方向。在深度学习中&#xff0c;梯度告诉我们如何调整神经网络参数&#xff0c;使损失函数最小化。 1.2 梯度的重要性 …