本文介绍: 按这里面来编写。

目录

​编辑

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);
    }

}
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 #连接池中的最小空闲连接

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;

    
    
}
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;
        }

    }





}

这个提前开启

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

  /**
     * 获取指定 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"));
    }

 //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 中储存的数字值增一。
    //如果 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 中储存的数字值减一。
    如果 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;
        }
    }
 /**
     * 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;
        }
    }

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;
        }

    }




}

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注