SpringBoot——实现对Redis五种数据类型的增删改查

一、添加Redis依赖

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

二、application.properties

# 应用名称
spring.application.name=springboot_redis
server.port=8085
#配置Redis,redis的host是虚拟机服务器上的IP地址,端口6379
spring.redis.host=127.0.0.1
spring.redis.port=6379

三、添加配置类

package com.ljx.springboot_redis.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.*;

import java.time.Duration;


/**
 * @Author: Ljx
 * @Date: 2021/12/1 13:34
 * @role:
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{
    private static final StringRedisSerializer STRING_SERIALIZER = new StringRedisSerializer();
    private static final GenericJackson2JsonRedisSerializer JACKSON__SERIALIZER = new GenericJackson2JsonRedisSerializer();

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        //设置缓存过期时间
        RedisCacheConfiguration redisCacheCfg=RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofHours(1))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(STRING_SERIALIZER))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(JACKSON__SERIALIZER));
        return RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
                .cacheDefaults(redisCacheCfg)
                .build();
    }

    @Bean
    @ConditionalOnMissingBean(name = "redisTemplate")
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){
        // 配置redisTemplate
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);
        // key序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // value序列化
        redisTemplate.setValueSerializer(JACKSON__SERIALIZER);
        // Hash key序列化
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        // Hash value序列化
        redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

四、测试

TestRedisString

package com.ljx.springboot_redis;

import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: Ljx
 * @Date: 2021/12/1 0:52
 * @role:
 */
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
class TestRedisString {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Test
    public void testSet(){
        //向数据库中保存 name heima
        redisTemplate.opsForValue().set("name","heima");

        //相关数据保存 name1 heima1  有效时间为10s
        redisTemplate.opsForValue().set("name1","heima1",10, TimeUnit.SECONDS);

        //替换 heima        heXXa  offset 索引位置是从0开始
        redisTemplate.opsForValue().set("name","XX",2);

        //当key不存在的时候,执行保存操作;当key存在时,什么都不做
        redisTemplate.opsForValue().setIfAbsent("name","heima");

        //批量保存
        Map<String,String> map = new HashMap<>();
        map.put("name2","heima2");
        map.put("name3","heima3");
        map.put("name3","heima3");

        redisTemplate.opsForValue().multiSet(map);

        //追加 当key存在时,会执行追加操作;当key不存在时,会执行保存操作
        redisTemplate.opsForValue().append("name5","heima");
    }


    @Test
    public void testGet(){
        //根据key获取value
        String value = redisTemplate.opsForValue().get("name");
        System.out.println(value);

        //首先根据key获取value,然后再根据value进行截取。从start位置截取到end位置【包含start和end】
        String name = redisTemplate.opsForValue().get("name", 5, 7);
        System.out.println(name);

        //批量获取
        List<String> keys = new ArrayList<>();
        keys.add("name2");
        keys.add("name3");
        keys.add("name4");
        List<String> values = redisTemplate.opsForValue().multiGet(keys);
        for (String s : values) {
            System.out.println(s);
        }

        //根据key获取value的长度
        Long size = redisTemplate.opsForValue().size("name");
        System.out.println(size);
    }


    @Test
    public void testIncrement(){
        redisTemplate.opsForValue().set("age","18");
//        自增1
        redisTemplate.opsForValue().increment("age");
        System.out.println(redisTemplate.opsForValue().get("age"));
//        自增6
        redisTemplate.opsForValue().increment("age",6);
        System.out.println(redisTemplate.opsForValue().get("age"));

//        自减
        redisTemplate.opsForValue().decrement("age");
    }

    //删除
    @Test
    public void testDelete(){
//        单个删除
        redisTemplate.delete("name");

        List<String> list = new ArrayList<>();
        list.add("name2");
        list.add("name3");
        list.add("name4");
//        批量删除
        redisTemplate.delete(list);
    }
}

TestRedisList

package com.ljx.springboot_redis;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.swing.*;
import java.util.List;

/**
 * @Author: Ljx
 * @Date: 2021/12/1 20:24
 * @role:
 */
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class TestRedisList {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //增加
    @Test
    public void testAdd(){
        //从左边添加一个元素
        redisTemplate.opsForList().leftPush("students","zhangshan");
        //从左边添加多个元素
        redisTemplate.opsForList().leftPush("students","lishi","wangwu");

        //从右边添加一个元素
        redisTemplate.opsForList().rightPush("students","zhangshan1");
        //从右边添加多个元素
        redisTemplate.opsForList().rightPush("students","lishi1","wangwu1");
    }

    @Test
    public void testFind(){
        //根据key和元素索引进行查询
        //0和正数代表从左边开始
        //负数代表从右边开始
        String students = redisTemplate.opsForList().index("students", 1);
        System.out.println(students);

        String students1 = redisTemplate.opsForList().index("students", -1);
        System.out.println(students1);

        //范围查询
        //根据key 【start,end】 包括首尾
        List<String> students2 = redisTemplate.opsForList().range("students", 0, 2);
        for (String s : students2) {
            System.out.println(s);
        }
    }
    //删除
    @Test
    public void testRemove(){
        //从左边删除第一个元素
        String s = redisTemplate.opsForList().leftPop("students");
        //从右边删除第一个元素
        String s1 = redisTemplate.opsForList().rightPop("students");

        //count > 0; 删除左边起第几个等于指定值的元素
        //count < 0; 删除右边起第几个等于指定值的元素
        //count = 0; 删除所有等于value的元素
        //删除左边起第二个wangwu
        redisTemplate.opsForList().remove("students",2,"wangwu");


    }
}

TestRedisHash

package com.ljx.springboot_redis;

import com.ljx.springboot_redis.uesr.Article;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Author: Ljx
 * @Date: 2021/12/1 13:07
 * @role:
 */
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class TestRedisHash {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void testPut(){
//        redisTemplate.setKeySerializer(new StringRedisSerializer());
//        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
//        redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
        Article article = new Article();
        article.setTitle("title");
        article.setCreateTime(new Date());
        article.setAuthor("lixiang");

        redisTemplate.opsForHash().put("article","1",article);
    }

    @Test
    public void testGet(){
//        redisTemplate.setKeySerializer(new StringRedisSerializer());
//        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
//        redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
        //判断hashkey是否存在
//        Boolean article = redisTemplate.opsForHash().hasKey("article", "2");
//        System.out.println(article);
//
//        //根据key和hashkey获取操作
//        Article article1 = (Article) redisTemplate.opsForHash().get("article", "2");
//        System.out.println(article1);


//        //根据key获取所有的hashkey
//        Set<String> set = redisTemplate.opsForHash().keys("article");
//        for (Object s : set) {
//            System.out.println(s);
//        }


        List<Article> articles = redisTemplate.opsForHash().values("article");
        for (Article article : articles) {
            System.out.println(article);
        }

        Map<String,Article> map = redisTemplate.opsForHash().entries("article");
        for (Map.Entry<String, Article> entry : map.entrySet()) {
            System.out.println(entry.getKey()+":"+entry.getValue());
        }
    }

    //删除
    @Test
    public void testDelete(){
        //当hash中的数据全被删除后,整个hash就没了
        redisTemplate.opsForHash().delete("article","1","2");
    }
}

Article

package com.ljx.springboot_redis.uesr;

import javax.xml.crypto.Data;
import java.io.Serializable;
import java.util.Date;

/**
 * @Author: Ljx
 * @Date: 2021/12/1 13:12
 * @role:
 */
public class Article implements Serializable {
    private String author;
    private Data createTime;
    private String title;

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public Data getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Data createTime) {
        this.createTime = createTime;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    @Override
    public String toString() {
        return "Article{" +
                "author='" + author + '\'' +
                ", createTime=" + createTime +
                ", title='" + title + '\'' +
                '}';
    }

    public void setCreateTime(Date date) {
    }
}

TestRedisSet

package com.ljx.springboot_redis;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;
import java.util.Set;

/**
 * @Author: Ljx
 * @Date: 2021/12/1 20:48
 * @role:
 */
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class TestRedisSet {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //增加
    @Test
    public void testAdd(){
        redisTemplate.opsForSet().add("Students","zhangsan","lishi","wangwu","Zhangsan");
    }

    //查询
    @Test
    public void testFind(){
        //查询所有元素
        Set<String> students = redisTemplate.opsForSet().members("Students");
        for (String student : students) {
            System.out.println(student);
        }

        //随机获取一个元素
        String students1 = redisTemplate.opsForSet().randomMember("Students");
        System.out.println(students1);

        //随机获取多个元素【可能会重复】
        List<String> list = redisTemplate.opsForSet().randomMembers("Students", 2);
        for (String s : list) {
            System.out.println(s);
        }
    }

    //删除
    @Test
    public void testRemove(){
        //移除元素,并返回移除成功个数
        Long remove = redisTemplate.opsForSet().remove("Students", "zhangsan", "wangwu");
        System.out.println(remove);

        //随机移除指定集合中的多少个元素
        List<String> students = redisTemplate.opsForSet().pop("Students", 2);
        for (String student : students) {
            System.out.println(student);
        }
    }

    //多集合操作
    @Test
    public void testMoreSet(){
        redisTemplate.opsForSet().add("names1","zhangsan","li","wangwu");
        redisTemplate.opsForSet().add("names2","zhangsan","li","zhaoliu");

        //取交集
        Set<String> intersect = redisTemplate.opsForSet().intersect("names1", "names2");
        for (String s : intersect) {
            System.out.println(s);
        }
        //取并集
        Set<String> union = redisTemplate.opsForSet().union("names1", "names2");
        for (String s : union) {
            System.out.println(s);
        }
        //取差集[第一个集合中存在,但第二个集合中不存在的元素]
        Set<String> difference = redisTemplate.opsForSet().difference("names2", "names1");
        for (String s : difference) {
            System.out.println(s);
        }

    }
}


TestRedisZSet

package com.ljx.springboot_redis;

import org.junit.Before;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.Set;

@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
class TestRedisZSet {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Test
    public void testAdd(){
        redisTemplate.opsForZSet().add("student","wangwu",60);
        redisTemplate.opsForZSet().add("student","lishi",100);
        redisTemplate.opsForZSet().add("student","zhangshan",90);
    }

//    分数的增减
    @Test
    public void testScore(){
        // 增加分数
        redisTemplate.opsForZSet().incrementScore("student","wangwu",30);

        // 减少分数
        redisTemplate.opsForZSet().incrementScore("student","wangwu",-50);
    }

    // 查询一个元素的信息
    @Test
    public void testFindOne(){
        //查询一个元素的分数
        Double score = redisTemplate.opsForZSet().score("student", "wangwu");
        System.out.println(score);

        //查询一个元素在集合中的排名  排名从0开始
        Long rank = redisTemplate.opsForZSet().rank("student", "zhangshan");
        System.out.println(rank);

    }

    //根据区间获取列表
    @Test
    public void testFindList(){
        //根据排名区间获取元素列表
        Set<String> students = redisTemplate.opsForZSet().range("student",0,2);
        for (String student : students) {
            System.out.println(student);
        }

        System.out.println("-------------");
        Set<ZSetOperations.TypedTuple<String>> student = redisTemplate.opsForZSet().rangeWithScores("student", 0, 2);
        for (ZSetOperations.TypedTuple<String> stringTypedTuple : student) {
            System.out.println(stringTypedTuple.getValue()+"同学,得了"+stringTypedTuple.getScore()+"分");
        }
        System.out.println("-----------------------------");
        //根据排名区间获取元素列表
        Set<String> students1 = redisTemplate.opsForZSet().rangeByScore("student",50,100);
        for (String student1 : students1) {
            System.out.println(student1);
        }

        System.out.println("-------------");
        Set<ZSetOperations.TypedTuple<String>> student1 = redisTemplate.opsForZSet().rangeByScoreWithScores("student", 50, 100);
        for (ZSetOperations.TypedTuple<String> stringTypedTuple : student1) {
            System.out.println(stringTypedTuple.getValue()+"同学,得了"+stringTypedTuple.getScore()+"分");
        }
    }


    //统计
    @Test
    public void testCount(){
        //统计一个集合中元素
        Long student = redisTemplate.opsForZSet().zCard("student");
        System.out.println(student);

        //根据一个分数区间统计元素数量
        Long count = redisTemplate.opsForZSet().count("student", 50, 100);
        System.out.println(count);
    }

    //删除
    @Test
    public void testRemove(){
        //根据key-value删除 value允许传入多个
        redisTemplate.opsForZSet().remove("student","zhangsan","lisi");

        //根据排名区间删除
        redisTemplate.opsForZSet().removeRange("student",0,1);

        //根据分数区间删除
        redisTemplate.opsForZSet().removeRangeByScore("student",70,90);
    }
}


版权声明:本文为qq_52006948原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。