当前位置: 首页 > news >正文

编写RedisUtil来操作Redis

目录

​编辑

Redis中文网

第一步:建springboot项目

第二步:导依赖

第三步:启动类

第四步:yml

第五步:Redis配置类

第六步:测试类

第七步:编写工具类 RedisUtil

第八步:编写和测试

普通缓存放入:String类型

获取指定 key 所储存的字符串值的长度

Get 命令用于获取指定 key 的值

Redis Incr 命令将 key 中储存的数字值增一。

Redis Decr 命令将 key 中储存的数字值减一。

普通缓存放入并设置时间

key 中储存的数字加上指定的增量值。

Redis Mget 命令返回所有(一个或多个)给定 key 的值。 如果给定的 key 里面,有某个 key 不存在,那么这个 key 返回特殊值 nil 。


Redis中文网

按这里面来编写

第一步:建springboot项目

第二步:导依赖

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.4.5</version><relativePath/></parent><groupId>com.itheima</groupId><artifactId>springdataredis_demo</artifactId><version>1.0-SNAPSHOT</version><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><version>2.4.5</version></plugin></plugins></build>
</project>

第三步:启动类

package com.itheima;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class App {public static void main(String[] args) {SpringApplication.run(App.class,args);}}

第四步:yml

spring:application:name: springdataredis_demo#Redis相关配置redis:host: localhostport: 6379#password: 123456database: 0 #操作的是0号数据库jedis:#Redis连接池配置pool:max-active: 8 #最大连接数max-wait: 1ms #连接池最大阻塞等待时间max-idle: 4 #连接池中的最大空闲连接min-idle: 0 #连接池中的最小空闲连接

第五步:Redis配置类

package com.itheima.config;import org.springframework.cache.annotation.CachingConfigurerSupport;
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.StringRedisSerializer;/*** Redis配置类*/@Configuration
public class RedisConfig extends CachingConfigurerSupport {@Beanpublic RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();//默认的Key序列化器为:JdkSerializationRedisSerializer//设置新的y序列化器redisTemplate.setKeySerializer(new StringRedisSerializer());redisTemplate.setHashKeySerializer(new StringRedisSerializer());redisTemplate.setConnectionFactory(connectionFactory);return redisTemplate;}}

第六步:测试类

package com.itheima.test;import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;/*** @Author lpc* @Date 2024 01 16 14 52**/@SpringBootTest
@RunWith(SpringRunner.class)
public class RedisUtil {@Autowiredprivate RedisUtil redisUtil;}

第七步:编写工具类 RedisUtil

package com.itheima.utils;import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;import javax.annotation.Resource;/*** @Author lpc* @Date 2024 01 16 14 40**/@Component //是一个通用的Spring注解,用于将类标记为一个组件,使Spring容器能够自动检测并将其实例化为一个Spring Bean。
public class RedisUtil {/*** 这段代码实现了将一个用于操作Redis数据库的RedisTemplate对象注入到当前类中,以便于进行Redis相关操作。*/@Resourceprivate RedisTemplate<String, Object> redisTemplate;/*** 详解:* 1.创建一个RedisTemplate对象:通过将redisTemplate字段声明为RedisTemplate<String, Object>类型,可以创建一个用于操作Redis数据库的RedisTemplate对象。* 2.实现Redis操作:通过使用redisTemplate对象,您可以执行各种Redis操作,如插入数据、查询数据、更新数据等。由于字段的泛型参数是<String, Object>,这意味着Redis的Key是String类型,Value是Object类型。您可以根据需要进行类型转换。* 3.依赖注入:使用@Resource注解,将与RedisTemplate<String, Object>类型兼容的Bean注入到redisTemplate字段中。这意味着在Spring容器中配置了一个与RedisTemplate<String, Object>匹配的Bean,并且该Bean会在当前类的实例化过程中自动注入到redisTemplate字段上。*/// ============================String=============================/*** 普通缓存放入** @param key   键* @param value 值* @return true成功 false失败*/public boolean set(String key, Object value) {try {redisTemplate.opsForValue().set(key, value);return true;} catch (Exception e) {e.printStackTrace();return false;}}}

第八步:编写和测试

普通缓存放入:String类型

这个提前开启

 @Testpublic void testString(){redisUtil.set("cosplay","liuhua");}

获取指定 key 所储存的字符串值的长度

  /*** 获取指定 key 所储存的字符串值的长度* @param key* @return*///Redis Strlen 命令用于获取指定 key 所储存的字符串值的长度。当 key 储存的不是字符串值时,返回一个错误。public Long strlen(String key){try{return redisTemplate.opsForValue().size(key);}catch (Exception e){e.printStackTrace();return null; // 或者抛出自定义的异常}}
 @Testpublic void testString(){redisUtil.set("cosplay","liuhua");System.out.println( redisUtil.strlen("cosplay"));}

Get 命令用于获取指定 key 的值

 //Redis Get 命令用于获取指定 key 的值。如果 key 不存在,返回 nil 。如果key 储存的值不是字符串类型,返回一个错误。/*** 普通缓存获取** @param key               键* @param* @return 值* 解释:如何key是null,就返回null; 不是就返回Redis里面的value*/public Object get(String key) {return key == null ? null : redisTemplate.opsForValue().get(key);}
 @Testpublic void testString(){redisUtil.set("cosplay","liuhua");System.out.println( redisUtil.strlen("cosplay"));System.out.println(redisUtil.get("cosplay"));}

Redis Incr 命令将 key 中储存的数字值增一。

 //Redis Incr 命令将 key 中储存的数字值增一。//如果 key 不存在,那么 key 的值会先被初始化为 0 ,然后再执行 INCR 操作。//如果值包含错误的类型,或字符串类型的值不能表示为数字,那么返回一个错误。//本操作的值限制在 64 位(bit)有符号数字表示之内。/*** 递增** @param key   键* @param delta 要增加几(大于0)* @return*/public long incr(String key, long delta) {if (delta < 0) {throw new RuntimeException("递增因子必须大于0");}return redisTemplate.opsForValue().increment(key, delta);}
 @Testpublic void testString(){String key = "test_key";long delta = 1;// 调用递增方法long result = redisUtil.incr(key, delta);System.out.println(result);}

Redis Decr 命令将 key 中储存的数字值减一。

/* Redis Decr 命令将 key 中储存的数字值减一。如果 key 不存在,那么 key 的值会先被初始化为 0 ,然后再执行 DECR 操作。如果值包含错误的类型,或字符串类型的值不能表示为数字,那么返回一个错误。本操作的值限制在 64 位(bit)有符号数字表示之内。*//*** 递减** @param key   键* @param delta 要减少几(小于0)* @return*/public long decr(String key, long delta) {if (delta < 0) {throw new RuntimeException("递减因子必须大于0");}return redisTemplate.opsForValue().increment(key, -delta);}
 @Testpublic void testString2(){String key = "test_key2";long delta = 30;// 调用递增方法long result = redisUtil.decr(key, delta);System.out.println(result);}

普通缓存放入并设置时间

/*** 普通缓存放入并设置时间** @param key   键* @param value 值* @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期* @return true成功 false 失败*/public boolean set(String key, Object value, long time) {try {if (time > 0) {redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);} else {set(key, value);}return true;} catch (Exception e) {e.printStackTrace();return false;}}

key 中储存的数字加上指定的增量值。

 /*** Incrby 命令将 key 中储存的数字加上指定的增量值。* @param key* @param increment* @return* 如果值包含错误的类型,或字符串类型的值不能表示为数字,那么返回一个错误:*/public long incrBy(String key, long increment) {try {return redisTemplate.opsForValue().increment(key, increment);} catch (Exception e) {e.printStackTrace();return 0; //返回一个0}}

Redis Mget 命令返回所有(一个或多个)给定 key 的值。 如果给定的 key 里面,有某个 key 不存在,那么这个 key 返回特殊值 nil 。

/*** mget 命令返回所有(一个或多个)给定 key 的值。* 如果给定的 key 里面,有某个 key 不存在,那么这个 key 返回特殊值 nil 。* @param keys* @return*/public List<Object> mget(String... keys) {try {return redisTemplate.opsForValue().multiGet(Arrays.asList(keys));} catch (Exception e) {e.printStackTrace();return null;}}

Redis Getset 命令用于设置指定 key 的值,并返回 key 旧的值。

/*** 设置指定键的新值,并返回旧值** @param key   键* @param value 新值* @return 旧值*/public Object getSet(String key,Object value){try{return redisTemplate.opsForValue().getAndSet(key, value);}catch (Exception e){e.printStackTrace();return  null;}}

完整工具类

package com.itheima.utils;import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;/*** @Author lpc* @Date 2024 01 16 14 40**/@Component //是一个通用的Spring注解,用于将类标记为一个组件,使Spring容器能够自动检测并将其实例化为一个Spring Bean。
public class RedisUtil {/*** 这段代码实现了将一个用于操作Redis数据库的RedisTemplate对象注入到当前类中,以便于进行Redis相关操作。*/@Resourceprivate RedisTemplate<String, Object> redisTemplate;/*** 详解:* 1.创建一个RedisTemplate对象:通过将redisTemplate字段声明为RedisTemplate<String, Object>类型,可以创建一个用于操作Redis数据库的RedisTemplate对象。* 2.实现Redis操作:通过使用redisTemplate对象,您可以执行各种Redis操作,如插入数据、查询数据、更新数据等。由于字段的泛型参数是<String, Object>,这意味着Redis的Key是String类型,Value是Object类型。您可以根据需要进行类型转换。* 3.依赖注入:使用@Resource注解,将与RedisTemplate<String, Object>类型兼容的Bean注入到redisTemplate字段中。这意味着在Spring容器中配置了一个与RedisTemplate<String, Object>匹配的Bean,并且该Bean会在当前类的实例化过程中自动注入到redisTemplate字段上。*/// ============================String类型=============================//Redis SET 命令用于设置给定 key 的值。如果 key 已经存储其他值, SET 就覆写旧值,且无视类型。/*** 普通缓存放入** @param key   键* @param value 值* @return true成功 false失败*/public boolean set(String key, Object value) {try {redisTemplate.opsForValue().set(key, value);return true;} catch (Exception e) {e.printStackTrace();return false;}}//Redis Get 命令用于获取指定 key 的值。如果 key 不存在,返回 nil 。如果key 储存的值不是字符串类型,返回一个错误。/*** 普通缓存获取** @param key               键* @param* @return 值* 解释:如何key是null,就返回null; 不是就返回Redis里面的value*/public Object get(String key) {return key == null ? null : redisTemplate.opsForValue().get(key);}/*** 获取指定 key 所储存的字符串值的长度* @param key* @return*///Redis Strlen 命令用于获取指定 key 所储存的字符串值的长度。当 key 储存的不是字符串值时,返回一个错误。public Long strlen(String key){try{return redisTemplate.opsForValue().size(key);}catch (Exception e){e.printStackTrace();return null; // 或者抛出自定义的异常}}//Redis Incr 命令将 key 中储存的数字值增一。//如果 key 不存在,那么 key 的值会先被初始化为 0 ,然后再执行 INCR 操作。//如果值包含错误的类型,或字符串类型的值不能表示为数字,那么返回一个错误。//本操作的值限制在 64 位(bit)有符号数字表示之内。/*** 递增** @param key   键* @param delta 要增加几(大于0)* @return*/public long incr(String key, long delta) {if (delta < 0) {throw new RuntimeException("递增因子必须大于0");}return redisTemplate.opsForValue().increment(key, delta);}/* Redis Decr 命令将 key 中储存的数字值减一。如果 key 不存在,那么 key 的值会先被初始化为 0 ,然后再执行 DECR 操作。如果值包含错误的类型,或字符串类型的值不能表示为数字,那么返回一个错误。本操作的值限制在 64 位(bit)有符号数字表示之内。*//*** 递减** @param key   键* @param delta 要减少几(小于0)* @return*/public long decr(String key, long delta) {if (delta < 0) {throw new RuntimeException("递减因子必须大于0");}return redisTemplate.opsForValue().increment(key, -delta);}/*** 普通缓存放入并设置时间** @param key   键* @param value 值* @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期* @return true成功 false 失败*/public boolean set(String key, Object value, long time) {try {if (time > 0) {redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);} else {set(key, value);}return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** Incrby 命令将 key 中储存的数字加上指定的增量值。* @param key* @param increment* @return* 如果值包含错误的类型,或字符串类型的值不能表示为数字,那么返回一个错误:*/public long incrBy(String key, long increment) {try {return redisTemplate.opsForValue().increment(key, increment);} catch (Exception e) {e.printStackTrace();return 0; //返回一个0}}/*** mget 命令返回所有(一个或多个)给定 key 的值。* 如果给定的 key 里面,有某个 key 不存在,那么这个 key 返回特殊值 nil 。* @param keys* @return*/public List<Object> mget(String... keys) {try {return redisTemplate.opsForValue().multiGet(Arrays.asList(keys));} catch (Exception e) {e.printStackTrace();return null;}}/*** 设置指定键的新值,并返回旧值** @param key   键* @param value 新值* @return 旧值*/public Object getSet(String key,Object value){try{return redisTemplate.opsForValue().getAndSet(key, value);}catch (Exception e){e.printStackTrace();return  null;}}}

相关文章:

  • Java中的finally字句
  • 006.Oracle事务处理
  • python爬虫如何写,有哪些成功爬取的案例
  • pytest -- 进阶使用详解
  • iproute 随手记
  • Spring Boot程序的打包与运行:构建高效部署流程
  • HarmonyOS—开发环境诊断的功能
  • MybatisPlus框架入门级理解
  • 安捷伦N5244A网络分析仪43.5GHz
  • 【PHP】PHP利用ffmreg获取音频、视频的详细信息
  • tomcat与servlet
  • 【Linux】信号量基于环形队列的生产消费模型
  • [AI]文心一言出圈的同时,NLP处理下的ChatGPT-4.5最新资讯
  • 【办公软件篇】软件启动器Lucy打造自己的工具箱
  • vue解决部署文件缓存方式
  • 网络传输文件的问题
  • 分享一款快速APP功能测试工具
  • 【翻译】babel对TC39装饰器草案的实现
  • EventListener原理
  • interface和setter,getter
  • Object.assign方法不能实现深复制
  • oldjun 检测网站的经验
  • vagrant 添加本地 box 安装 laravel homestead
  • 给初学者:JavaScript 中数组操作注意点
  • 码农张的Bug人生 - 见面之礼
  • 前嗅ForeSpider采集配置界面介绍
  • 使用 @font-face
  • 我建了一个叫Hello World的项目
  • 小程序button引导用户授权
  • 一、python与pycharm的安装
  •  一套莫尔斯电报听写、翻译系统
  • Semaphore
  • 蚂蚁金服CTO程立:真正的技术革命才刚刚开始
  • ​ 全球云科技基础设施:亚马逊云科技的海外服务器网络如何演进
  • #我与Java虚拟机的故事#连载12:一本书带我深入Java领域
  • $分析了六十多年间100万字的政府工作报告,我看到了这样的变迁
  • (0)Nginx 功能特性
  • (1) caustics\
  • (4)STL算法之比较
  • (4.10~4.16)
  • (教学思路 C#之类三)方法参数类型(ref、out、parmas)
  • (三)Honghu Cloud云架构一定时调度平台
  • (原創) 如何安裝Linux版本的Quartus II? (SOC) (Quartus II) (Linux) (RedHat) (VirtualBox)
  • (原創) 系統分析和系統設計有什麼差別? (OO)
  • (转)程序员技术练级攻略
  • ***测试-HTTP方法
  • .dwp和.webpart的区别
  • .NET 跨平台图形库 SkiaSharp 基础应用
  • .NetCore 如何动态路由
  • /ThinkPHP/Library/Think/Storage/Driver/File.class.php  LINE: 48
  • @EnableAsync和@Async开始异步任务支持
  • [20160902]rm -rf的惨案.txt
  • [Android]使用Android打包Unity工程
  • [Asp.net mvc]国际化
  • [bzoj1901]: Zju2112 Dynamic Rankings