search
HomeDatabaseRedisHow to integrate SpringBoot and Redis

How to integrate SpringBoot and Redis

May 30, 2023 pm 12:03 PM
redisspringboot

Integration of SpringBoot and non-relational database Redis

(1) Add Spring Data Redis dependency starter

How to integrate SpringBoot and Redis

Introduce this dependency to create a project, The following dependencies will appear in the project pom.xml file:

How to integrate SpringBoot and Redis

(2) Write the entity class

Person:

package com.hardy.springbootdataredis.domain;import org.springframework.data.annotation.Id;import org.springframework.data.redis.core.RedisHash;import org.springframework.data.redis.core.index.Indexed;/**
 * @Author: HardyYao
 * @Date: 2021/6/15 */@RedisHash("persons")   // 指定操作实体类对象在Redis数据库中的存储空间public class Person {

    @Id // 标识实体类主键private String id;

    @Indexed // 标识对应属性在Redis数据库中生成二级索引private String firstname;

    @Indexedprivate String lastname;private Address address;public String getId() {return id;
    }public void setId(String id) {this.id = id;
    }public String getFirstname() {return firstname;
    }public void setFirstname(String firstname) {this.firstname = firstname;
    }public String getLastname() {return lastname;
    }public void setLastname(String lastname) {this.lastname = lastname;
    }public Address getAddress() {return address;
    }public void setAddress(Address address) {this.address = address;
    }

    @Overridepublic String toString() {return "Person{" +
                "id='" + id + ''' +
                ", firstname='" + firstname + ''' +
                ", lastname='" + lastname + ''' +
                ", address=" + address +
                '}';
    }
}

Address:

package com.hardy.springbootdataredis.domain;import org.springframework.data.redis.core.index.Indexed;/**
 * @Author: HardyYao
 * @Date: 2021/6/15 */public class Address {

    @Indexedprivate String city;

    @Indexedprivate String country;public String getCity() {return city;
    }public void setCity(String city) {this.city = city;
    }public String getCountry() {return country;
    }public void setCountry(String country) {this.country = country;
    }

    @Overridepublic String toString() {return "Address{" +
                "city='" + city + ''' +
                ", country='" + country + ''' +
                '}';
    }
}

In the above two entity classes, several annotations about data operations of the Redis database are involved:

  • @RedisHash("persons"): used to specify Manipulate the storage space of entity class objects in the Redis database. Here, it means that data operations for the Person entity class are stored in the storage space named persons in the Redis database.

  • @Id: used to identify the primary key of the entity class. In the Redis database, a HashKey in the form of a string is generated by default to represent the unique entity object ID. Of course, the ID can also be manually specified during data storage.

  • @Indexed: Used to specify to generate a secondary index for the corresponding attribute in the Redis database. When this annotation is used, the secondary index corresponding to the attribute will be generated in the database, which will make data query simple. The index name is the same as the attribute name.

(3) Writing the Repository interface

SpringBoot provides automated configuration for some common databases including Redis, which can simplify the data in the database by implementing the Repository interface. Perform operations of adding, deleting, checking and modifying:

package com.hardy.springbootdataredis.repository;import com.hardy.springbootdataredis.domain.Person;import org.springframework.data.repository.CrudRepository;import java.util.List;/**
 * @Author: HardyYao
 * @Date: 2021/6/15 */public interface PersonRepository extends CrudRepository<Person, String> {

    List<Person> findByAddress_City(String City);

}

Note: The Repository interface class written when operating the Redis database needs to inherit the lowest level CrudRepository interface instead of inheriting JpaRepository (JpaRepository is SpringBoot integrated JPA Unique). Of course, you can also import the JPA dependencies and Redis dependencies integrated by SpringBoot into the project pom.xml file at the same time, so that you can write an interface that inherits the JpaRepository interface to operate the Redis database.

(4) Redis database connection configuration

Add the Redis database connection configuration in the project’s global configuration file application.properties. The sample code is as follows:

# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=

(5) Write unit test method

package com.hardy.springbootdataredis;import com.hardy.springbootdataredis.domain.Address;import com.hardy.springbootdataredis.domain.Person;import com.hardy.springbootdataredis.repository.PersonRepository;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import java.util.List;

@SpringBootTestclass SpringbootdataRedisApplicationTests {

    @Autowiredprivate PersonRepository repository;

    @Testpublic void savePerson() {
        Person person = new Person();
        person.setFirstname("张");
        person.setLastname("三");
        Address address = new Address();
        address.setCity("北京");
        address.setCountry("中国");
        person.setAddress(address);// 向Redis数据库添加数据Person save = repository.save(person);
    }

    @Testpublic void selectPerson() {
        List<Person> list = repository.findByAddress_City("北京");for (Person person : list) {
            System.out.println(person);
        }
    }

}

(6) Integration test

Open the Redis client visual management tool, first connect to the local Redis server:

How to integrate SpringBoot and Redis

After the connection is successful, you can see that there is no data in the local Redis database:

How to integrate SpringBoot and Redis

Run the two test methods written above and view the console print results:

How to integrate SpringBoot and Redis

In order to verify that the save() method has indeed written the data to the local Redis database, open the Redis client visual management tool, refresh the data, and you can see that the data is successful. Written:

How to integrate SpringBoot and Redis

# As can be seen from the above figure: the data added by executing the save() method is successfully stored in the Redis database. In addition, a secondary index similar to address.city, firstname, lastname, etc. is formed on the left side of the database list. These secondary indexes are generated by adding the @Indexed annotation to the corresponding attributes when creating the Person class. At the same time, since the secondary index corresponding to the attribute is generated in the Redis database, specific data information can be queried through the secondary index. For example, repository.findByAddress_City ("Beijing") queries the data whose index value is Beijing through the address.city index. information. If the secondary index of the corresponding attribute is not set, the data result queried through the attribute index will be empty.

The above is the detailed content of How to integrate SpringBoot and 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
Is Redis a SQL or NoSQL Database? The Answer ExplainedIs Redis a SQL or NoSQL Database? The Answer ExplainedApr 18, 2025 am 12:11 AM

RedisisclassifiedasaNoSQLdatabasebecauseitusesakey-valuedatamodelinsteadofthetraditionalrelationaldatabasemodel.Itoffersspeedandflexibility,makingitidealforreal-timeapplicationsandcaching,butitmaynotbesuitableforscenariosrequiringstrictdataintegrityo

Redis: Improving Application Performance and ScalabilityRedis: Improving Application Performance and ScalabilityApr 17, 2025 am 12:16 AM

Redis improves application performance and scalability by caching data, implementing distributed locking and data persistence. 1) Cache data: Use Redis to cache frequently accessed data to improve data access speed. 2) Distributed lock: Use Redis to implement distributed locks to ensure the security of operation in a distributed environment. 3) Data persistence: Ensure data security through RDB and AOF mechanisms to prevent data loss.

Redis: Exploring Its Data Model and StructureRedis: Exploring Its Data Model and StructureApr 16, 2025 am 12:09 AM

Redis's data model and structure include five main types: 1. String: used to store text or binary data, and supports atomic operations. 2. List: Ordered elements collection, suitable for queues and stacks. 3. Set: Unordered unique elements set, supporting set operation. 4. Ordered Set (SortedSet): A unique set of elements with scores, suitable for rankings. 5. Hash table (Hash): a collection of key-value pairs, suitable for storing objects.

Redis: Classifying Its Database ApproachRedis: Classifying Its Database ApproachApr 15, 2025 am 12:06 AM

Redis's database methods include in-memory databases and key-value storage. 1) Redis stores data in memory, and reads and writes fast. 2) It uses key-value pairs to store data, supports complex data structures such as lists, collections, hash tables and ordered collections, suitable for caches and NoSQL databases.

Why Use Redis? Benefits and AdvantagesWhy Use Redis? Benefits and AdvantagesApr 14, 2025 am 12:07 AM

Redis is a powerful database solution because it provides fast performance, rich data structures, high availability and scalability, persistence capabilities, and a wide range of ecosystem support. 1) Extremely fast performance: Redis's data is stored in memory and has extremely fast read and write speeds, suitable for high concurrency and low latency applications. 2) Rich data structure: supports multiple data types, such as lists, collections, etc., which are suitable for a variety of scenarios. 3) High availability and scalability: supports master-slave replication and cluster mode to achieve high availability and horizontal scalability. 4) Persistence and data security: Data persistence is achieved through RDB and AOF to ensure data integrity and reliability. 5) Wide ecosystem and community support: with a huge ecosystem and active community,

Understanding NoSQL: Key Features of RedisUnderstanding NoSQL: Key Features of RedisApr 13, 2025 am 12:17 AM

Key features of Redis include speed, flexibility and rich data structure support. 1) Speed: Redis is an in-memory database, and read and write operations are almost instantaneous, suitable for cache and session management. 2) Flexibility: Supports multiple data structures, such as strings, lists, collections, etc., which are suitable for complex data processing. 3) Data structure support: provides strings, lists, collections, hash tables, etc., which are suitable for different business needs.

Redis: Identifying Its Primary FunctionRedis: Identifying Its Primary FunctionApr 12, 2025 am 12:01 AM

The core function of Redis is a high-performance in-memory data storage and processing system. 1) High-speed data access: Redis stores data in memory and provides microsecond-level read and write speed. 2) Rich data structure: supports strings, lists, collections, etc., and adapts to a variety of application scenarios. 3) Persistence: Persist data to disk through RDB and AOF. 4) Publish subscription: Can be used in message queues or real-time communication systems.

Redis: A Guide to Popular Data StructuresRedis: A Guide to Popular Data StructuresApr 11, 2025 am 12:04 AM

Redis supports a variety of data structures, including: 1. String, suitable for storing single-value data; 2. List, suitable for queues and stacks; 3. Set, used for storing non-duplicate data; 4. Ordered Set, suitable for ranking lists and priority queues; 5. Hash table, suitable for storing object or structured data.

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor