search
HomeDatabaseRedisHow does Java SpringBoot operate Redis?
How does Java SpringBoot operate Redis?Jun 03, 2023 pm 06:01 PM
javaredisspringboot

    Redis

    1. Add redis dependency

    spring Boot provides a component package for Redis integration: spring-boot-starter-data-redis, which depends on spring-data-redis and lettuce.

    In addition, there are two small details here:

    • In the Spring Boot 1.x era, the bottom layer of spring-data-redis used Jedis; in the 2.x era Replaced with Lettuce.

    • Lettuce depends on commons-pool2

    <!-- springboot整合redis--> 
    <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <!-- 使用 lettuce 时要加这个包;使用 jedis 时则不需要。-->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-pool2</artifactId>
    </dependency>

    2. Configuration file

    ## Redis 服务器地址
    spring.redis.host=localhost
    ## Redis 服务器连接端口
    spring.redis.port=6379
    ## Redis 数据库索引(默认为 0)
    spring.redis.database=0
    
    ## 以下非必须,有默认值
    ## Redis 服务器连接密码(默认为空)
    spring.redis.password=
    ## 连接池最大连接数(使用负值表示没有限制)默认 8
    spring.redis.lettuce.pool.max-active=8
    ## 连接池最大阻塞等待时间(使用负值表示没有限制)默认 -1
    spring.redis.lettuce.pool.max-wait=-1
    ## 连接池中的最大空闲连接 默认 8
    spring.redis.lett	uce.pool.max-idle=8
    ## 连接池中的最小空闲连接 默认 0
    spring.redis.lettuce.pool.min-idle=0

    3. Operation redis API

    In this unit test, we use redisTemplate to store a string "Hello Redis".

    Spring Data Redis has reclassified and encapsulated the api, encapsulating the same type of operations into Operation interface:

    ##ValueOperationsData operations of string typeListOperationslist type data operationSetOperationsset type data operationZSetOperations zset type data operationHashOperationsmap type data operation##
    //解决中文乱码问题
    @Configuration
    public class RedisConfig {
        
        @Bean
        public RedisTemplate redisTemplateInit(RedisConnectionFactory redisConnectionFactory) {
    
            RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
    
            redisTemplate.setConnectionFactory(redisConnectionFactory);
            //设置序列化Key的实例化对象
            redisTemplate.setKeySerializer(new StringRedisSerializer());
            //设置序列化Value的实例化对象
            redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    
            /**
             *
             * 设置Hash类型存储时,对象序列化报错解决
             */
            redisTemplate.setHashKeySerializer(new StringRedisSerializer());
            redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
            return redisTemplate;
        }
    }
    4, RedisTemplate and StringRedisTemplate
    Proprietary operations Description

    RedisTemplate looks more "powerful" than StringRedisTemplate because it does not require that the key and value types must be String.

    But obviously, this is contrary to the actual situation of Redis: at the smallest storage unit level, Redis can essentially only store strings and cannot store other types. From this point of view, StringRedisTemplate is more in line with the storage nature of Redis. How does RedisTemplate support any type by serializing values?.

    When using RedisTemplate to store objects, the address of the object will be saved for deserialization, which will greatly waste storage space. To solve this problem, use StringRedisTemplate, thinking that manual serialization and deserialization are required

     Users users = new Users();
     users.setId(2);
     users.setUsername("李四2");
     redisTemplate.opsForValue().set("user:2", JSON.toJSONString(users)); //存的时候序列化对象
     String u = redisTemplate.opsForValue().get("user:2");  //redis 只能返回字符串
     System.out.println("u="+ JSON.parseObject(u,Users.class));  //使用JSON工具反序化成对象

    If the spring-boot-starter-web dependency is not introduced in springboot, you need to add the jackson dependency.

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
    </dependency>

    5. SpringBoot operates String string

    a. Key expiration

    Automatic expiration problem of key. Redis can set a timeout when storing each data. time, the data will be automatically deleted after this time.

    Commonly used redis time units

    MINUTES

    : Minutes

    SECONDS

    : Seconds

    DAYS

    : Day

    //给user对象设置10分钟过期时间
    redisTemplate.opsForValue().set("user:1", JSON.toJSONString(users),10,TimeUnit.MINUTES );
    b, delete data

     //删除键
     redisTemplate.delete(key);
     //判断键是否存在
     boolean exists = redisTemplate.hasKey(key);
    6, SpringBoot operates Hash (hash)

    Generally when we store a key, it will naturally Using get/set to store is actually not a good idea. Redis will have a minimum memory to store a key. No matter how small the key you store is, it will not be less than this memory. Therefore, reasonable use of Hash can help us save a lot of memory.

    	@Test
        public void testHash() {
            String key = "tom";
            HashOperations<String, Object, Object> operations = redisTemplate.opsForHash();
            operations.put(key, "name", "tom");
            operations.put(key, "age", "20");
            String value= (String) operations.get(key,"name");
            System.out.println(value);
        }

    According to the above test case, it is found that three parameters need to be passed in during Hash set. The first is key, the second is field, and the third is the stored value. Generally speaking, Key represents a set of data, field is the attribute related to key, and value is the value corresponding to the attribute.

    7. SpringBoot operates List collection type

    Redis List has many application scenarios and is also one of the most important data structures of Redis. You can easily implement a queue using List. A typical application scenario of List is message queue. You can use the Push operation of List to store tasks in the List, and then the worker thread uses the POP operation to take out the task for execution.

    /**
         * 测试List
         * leftPush 将数据添加到key对应的现有数据的左边,也就是头部
         * leftPop  取队列最左边数据(从数据库移除)
         * rightPush 将数据添加到key对应的现有数据的右边,也就是尾部
         */
        @Test
        public void testList() {
            final String key = "list";
            ListOperations<String,Object> list = redisTemplate.opsForList();
            list.leftPush(key, "hello");
            list.leftPush(key, "world");
            list.leftPush(key, "goodbye");
          
            Object mete = list.leftPop("list");
            System.out.println("删除的元素是:"+mete); //删除 goodbye 
            String value = (String) list.leftPop(key);
    
            System.out.println(value.toString());
            
            // range(key, 0, 2) 从下标0开始找,找到2下标
            List<Object> values = list.range(key, 0, 2);
            for (Object v : values) {
                System.out.println("list range :" + v);
            }
        }
    }

    Redis List is implemented as a two-way linked list, which can support reverse search and traversal, making it more convenient to operate. However, it brings some additional memory overhead, many implementations within Redis, including sending buffer queues, etc. This data structure is also used.

    8. SpringBoot operates Set collection type

    The external functions provided by Redis Set are similar to List. It is a list function. The special thing is that Set can automatically deduplicate when you need it. Set is a good choice when storing a list of data and does not want duplicate data, and Set provides an important interface for determining whether a member is in a Set collection, which List cannot provide.

     /**
         * 测试Set
         */
        @Test
        public void testSet() {
            final String key = "set";
            SetOperations<String,Object> set = redisTemplate.opsForSet();
            set.add(key, "hello");
            set.add(key, "world");
            set.add(key, "world");
            set.add(key, "goodbye");
            Set<Object> values = set.members(key);
            for (Object v : values) {
                System.out.println("set value :" + v);
            }
           
            Boolean exist = set.isMember(key,"hello") //判断是否存在某个元素
            operations.move("set", "hello", "setcopy"); //把set集合中的hello元素放到setcopy 中
     
        }
    }

    9. SpringBoot operates ZSet collection type

    The usage scenarios of Redis ZSet are similar to Set. The difference is that Set is not automatically ordered, and ZSet can provide an additional priority (Score) through the user. ) parameters to sort the members, and it is insertion order, that is, automatic sorting.

    	/**
         * 测试ZSet
         * range(key, 0, 3) 从开始下标到结束下标,score从小到大排序
         * reverseRange  score从大到小排序
         * rangeByScore(key, 0, 3); 返回Score在0至3之间的数据
         */
        @Test
        public void testZset() {
            final String key = "lz";
            ZSetOperations<String,Object> zset = redisTemplate.opsForZSet();
            zset.add(key, "hello", 1);
            zset.add(key, "world", 6);
            zset.add(key, "good", 4);
            zset.add(key, "bye", 3);
    
            Set<Object> zsets = zset.range(key, 0, 3);
            for (Object v : zsets) {
                System.out.println("zset-A value :"+v);
            }
            
            System.out.println("=======");
            Set<Object> zsetB = zset.rangeByScore(key, 0, 3);
            for (Object v : zsetB) {
                System.out.println("zset-B value :"+v);
            }
        }
    }

    The above is the detailed content of How does Java SpringBoot operate Redis?. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    带你搞懂Java结构化数据处理开源库SPL带你搞懂Java结构化数据处理开源库SPLMay 24, 2022 pm 01:34 PM

    本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

    Java集合框架之PriorityQueue优先级队列Java集合框架之PriorityQueue优先级队列Jun 09, 2022 am 11:47 AM

    本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于PriorityQueue优先级队列的相关知识,Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的,下面一起来看一下,希望对大家有帮助。

    完全掌握Java锁(图文解析)完全掌握Java锁(图文解析)Jun 14, 2022 am 11:47 AM

    本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于java锁的相关问题,包括了独占锁、悲观锁、乐观锁、共享锁等等内容,下面一起来看一下,希望对大家有帮助。

    一起聊聊Java多线程之线程安全问题一起聊聊Java多线程之线程安全问题Apr 21, 2022 pm 06:17 PM

    本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

    详细解析Java的this和super关键字详细解析Java的this和super关键字Apr 30, 2022 am 09:00 AM

    本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

    Java基础归纳之枚举Java基础归纳之枚举May 26, 2022 am 11:50 AM

    本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

    java中封装是什么java中封装是什么May 16, 2019 pm 06:08 PM

    封装是一种信息隐藏技术,是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的方法;封装可以被认为是一个保护屏障,防止指定类的代码和数据被外部类定义的代码随机访问。封装可以通过关键字private,protected和public实现。

    归纳整理JAVA装饰器模式(实例详解)归纳整理JAVA装饰器模式(实例详解)May 05, 2022 pm 06:48 PM

    本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于设计模式的相关问题,主要将装饰器模式的相关内容,指在不改变现有对象结构的情况下,动态地给该对象增加一些职责的模式,希望对大家有帮助。

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    Repo: How To Revive Teammates
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    Hello Kitty Island Adventure: How To Get Giant Seeds
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    DVWA

    DVWA

    Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

    Atom editor mac version download

    Atom editor mac version download

    The most popular open source editor

    Dreamweaver Mac version

    Dreamweaver Mac version

    Visual web development tools

    PhpStorm Mac version

    PhpStorm Mac version

    The latest (2018.2.1) professional PHP integrated development tool

    SecLists

    SecLists

    SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.