编写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: localhost
    port: 6379
    #password: 123456
    database: 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 {

    @Bean
    public 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 {

 @Autowired
    private 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相关操作。
     */
    @Resource
    private 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类型

这个提前开启

 @Test
    public 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; // 或者抛出自定义的异常
        }
    }

 @Test
    public 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);
    }
 @Test
    public 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);
    }
 @Test
    public 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);
    }

 @Test
    public 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相关操作。
     */
    @Resource
    private 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;
        }

    }




}

  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值