编写RedisUtil来操作Redis

2024-01-17 15:20
文章标签 操作 redis 编写 redisutil

本文主要是介绍编写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;}}}

这篇关于编写RedisUtil来操作Redis的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/616461

相关文章

零基础学习Redis(10) -- zset类型命令使用

zset是有序集合,内部除了存储元素外,还会存储一个score,存储在zset中的元素会按照score的大小升序排列,不同元素的score可以重复,score相同的元素会按照元素的字典序排列。 1. zset常用命令 1.1 zadd  zadd key [NX | XX] [GT | LT]   [CH] [INCR] score member [score member ...]

如何编写Linux PCIe设备驱动器 之二

如何编写Linux PCIe设备驱动器 之二 功能(capability)集功能(capability)APIs通过pci_bus_read_config完成功能存取功能APIs参数pos常量值PCI功能结构 PCI功能IDMSI功能电源功率管理功能 功能(capability)集 功能(capability)APIs int pcie_capability_read_wo

动手学深度学习【数据操作+数据预处理】

import osos.makedirs(os.path.join('.', 'data'), exist_ok=True)data_file = os.path.join('.', 'data', 'house_tiny.csv')with open(data_file, 'w') as f:f.write('NumRooms,Alley,Price\n') # 列名f.write('NA

线程的四种操作

所属专栏:Java学习        1. 线程的开启 start和run的区别: run:描述了线程要执行的任务,也可以称为线程的入口 start:调用系统函数,真正的在系统内核中创建线程(创建PCB,加入到链表中),此处的start会根据不同的系统,分别调用不同的api,创建好之后的线程,再单独去执行run(所以说,start的本质是调用系统api,系统的api

Java IO 操作——个人理解

之前一直Java的IO操作一知半解。今天看到一个便文章觉得很有道理( 原文章),记录一下。 首先,理解Java的IO操作到底操作的什么内容,过程又是怎么样子。          数据来源的操作: 来源有文件,网络数据。使用File类和Sockets等。这里操作的是数据本身,1,0结构。    File file = new File("path");   字

Redis中使用布隆过滤器解决缓存穿透问题

一、缓存穿透(失效)问题 缓存穿透是指查询一个一定不存在的数据,由于缓存中没有命中,会去数据库中查询,而数据库中也没有该数据,并且每次查询都不会命中缓存,从而每次请求都直接打到了数据库上,这会给数据库带来巨大压力。 二、布隆过滤器原理 布隆过滤器(Bloom Filter)是一种空间效率很高的随机数据结构,它利用多个不同的哈希函数将一个元素映射到一个位数组中的多个位置,并将这些位置的值置

MySQL——表操作

目录 一、创建表 二、查看表 2.1 查看表中某成员的数据 2.2 查看整个表中的表成员 2.3 查看创建表时的句柄 三、修改表 alter 3.1 重命名 rename 3.2 新增一列 add 3.3 更改列属性 modify 3.4 更改列名称 change 3.5 删除某列 上一篇博客介绍了库的操作,接下来来看一下表的相关操作。 一、创建表 create

Lua 脚本在 Redis 中执行时的原子性以及与redis的事务的区别

在 Redis 中,Lua 脚本具有原子性是因为 Redis 保证在执行脚本时,脚本中的所有操作都会被当作一个不可分割的整体。具体来说,Redis 使用单线程的执行模型来处理命令,因此当 Lua 脚本在 Redis 中执行时,不会有其他命令打断脚本的执行过程。脚本中的所有操作都将连续执行,直到脚本执行完成后,Redis 才会继续处理其他客户端的请求。 Lua 脚本在 Redis 中原子性的原因

封装MySQL操作时Where条件语句的组织

在对数据库进行封装的过程中,条件语句应该是相对难以处理的,毕竟条件语句太过于多样性。 条件语句大致分为以下几种: 1、单一条件,比如:where id = 1; 2、多个条件,相互间关系统一。比如:where id > 10 and age > 20 and score < 60; 3、多个条件,相互间关系不统一。比如:where (id > 10 OR age > 20) AND sco

laravel框架实现redis分布式集群原理

在app/config/database.php中配置如下: 'redis' => array('cluster' => true,'default' => array('host' => '172.21.107.247','port' => 6379,),'redis1' => array('host' => '172.21.107.248','port' => 6379,),) 其中cl