In the project, the access to data is often the direct access to the database, but if the access to the data is very large or very frequent, it will be a great pressure on the database, and even cause the database crash. In order to solve this kind of problem, REDis database stands out, Redis database appears as a non-relational database halo show in front of the vast number of program apes, later redis iteration version support cache data, login session state (distributed session sharing), etc.. It is used in large enterprise projects as a form of memory caching.
This section focuses on how to use Redis in a SpringBoot project.
1. A brief introduction to Redis
Redis is a high performance key-value non-relational database (NoSql) that is completely open source and free and complies with the BSD protocol. Redis and other key-value caching products have the following three characteristics:
- Redis supports data persistence, saving data in memory to disk, which can be reloaded for use upon restart.
- Redis not only supports simple key-value type data, but also provides the storage of list, set, zset, hash and other data structures.
- Redis supports data backup, namely, data backup in master-slave mode.
1.1 Data Structure introduction
Redis can store mappings between keys and five different data structure types: String, List, Set, Hash, and Zset.
Structure type
Structure to store values
Ability to read and write
String
It can be a string, integer, or floating point
Perform an operation on the entire string or part of a string; Objects and floating-point numbers perform increment or Decrement
List
A linked list in which each node contains a string
Push or pop elements from both ends of the list; Trim the list according to the offset; Read single or multiple elements; Find or remove elements based on their value
Set
An unorderedcollection that contains strings, and each contained string is unique and different
Add, get, and remove individual elements Checks if an element exists in a collection; Calculate intersection, union and difference sets; Show off randomly fetching elements from a collection
Hash
An unordered hash table containing key-value pairs
Add, get, and remove single key-value pairs; Gets all key-value pairs
Zset
An ordered mapping between a string member and a floating-point score. The order of elements is determined by the size of the score
Add, get, and delete individual elements; Retrieves elements based on a range of points or members
2.2 advantage of Redis
- High performance – Redis can read 110,000 times /s and write 81,000 times /s.
- Rich data types – Redis supports binary case Strings, Lists, Hashes, Sets and Ordered Sets data type operations.
- Atomic – All operations in Redis are atomic, meaning that they either succeed or fail at all. Individual operations are atomic. Multiple operations also support transactions, namely atomicity, wrapped in MULTI and EXEC instructions.
- Rich features – Redis also supports publish/subscribe, notifications, key expiration, and more.
2.3 What is the difference between Redis and other key-value stores?
- Redis has more complex data structures and provides atomic operations on them, which is a different evolutionary path from other databases. Redis data types are transparent to programmers while being based on basic data structures without additional abstractions.
- Redis runs in memory but can persist to disk, so memory is a tradeoff for high-speed reads and writes to different data sets, since the amount of data cannot be greater than hardware memory. Another advantage of an in-memory database is that it is much easier to operate in memory than the same complex data structures on disk, allowing Redis to do a lot of things with a lot of internal complexity. At the same time, they are compact in terms of disk formats and are produced in an appending manner because they do not require random access.
2. Install Redis
Download Linux or Windows version according to different needs, currently Redis website only Linux version, but since most developers are still based on Windows platform development, all GitHub technical people based on Linux platform Redis implementation of Windows version, Good news for Windows development.
2.1 Download Redis for Windows
Go directly to Github at github.com/MSOpenTech/… , download the latest Windows X64 zip package, as shown below:
Download the second. Zip, no installation, decompression can be used directly, after decompression, as shown below:
2.2 start the Redis
Redis.windows. conf is the redis configuration file. Related parameters, such as port, can be configured here. I use the default parameters and do not change them now. Double-click Redis-server. exe to start, as shown in the following figure, the startup is successful.
Redis is used in SpringBoot
Use Redis as a baseline for the previously built project.
3.1 Adding the Redis dependency package
Add the following to the project’s POM.xml:
<! <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>Copy the code
3.2 Configuring the Redis Database Connection
Configure the redis database connection information in application.properties as follows:
Port =6379 #redis database index (default: 0) Spring. Redis. Database = 0 # connection pool maximum number of connections (use a negative value indicates no limit) spring. Redis. Jedis. Pool. Max - active = 50 # connection pool biggest jam waiting time (use a negative value indicates no limit) Spring. Redis. Jedis. Pool. Max - wait = 3000 #, the lion's share of the connection pool free connection spring. Redis. Jedis. Pool. The Max - idle = # 20 minimum idle connections in the connection pool Spring. Redis. Jedis. Pool. Min - idle = 2 # connection timeout time (milliseconds) spring. Redis. Timeout = 5000Copy the code
3.3 Writing Redis operation tool classes
Wrap the RedisTemplate instance as a utility class to facilitate data manipulation on Redis.
com.xcbeyond.springboot.redis.RedisUtils.java
package com.xcbeyond.springboot.redis; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; </br> * (based on RedisTemplate) * @author xcbeyond * jul 19, 2018, 2:56:24 PM */ @Component Public class RedisUtils { @Autowired private RedisTemplate<String, String> redisTemplate; Public String get(final String key) {return redisTemplate.opsForValue().get(key); } /** * public Boolean set(final String key, String value) {Boolean result = false; try { redisTemplate.opsForValue().set(key, value); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /** * public Boolean getAndSet(final String key, String value) {Boolean result = false; try { redisTemplate.opsForValue().getAndSet(key, value); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /** * delete cache */ public Boolean delete(final String key) {Boolean result = false; try { redisTemplate.delete(key); result = true; } catch (Exception e) { e.printStackTrace(); } return result; }}Copy the code
3.4 test
Write a test case class to complete reading and writing to Redis.
/springboot/src/test/java/com/xcbeyond/springboot/redis/RedisTest.java
package com.xcbeyond.springboot.redis; import javax.annotation.Resource; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; / * * * * @ author xcbeyond 3:08:04 * * on July 19, 2018 afternoon / @ RunWith (SpringJUnit4ClassRunner. Class) @ SpringBootTest public class RedisTest { @Resource private RedisUtils redisUtils; / / @test public void set() {redisUtils. Set ("redis_key", "redis_vale"); } @test public void get() {String value = redisUtils. Get ("redis_key"); System.out.println(value); }}Copy the code
After executing the test method SET, you can log in to Redis to see if the data was successfully inserted.
(RedisDesktopManager visualization tool is recommended for viewing)
4, summarize
This chapter is just a brief introduction to how to use Redis in SpringBoot, the use of Redis is far more than this, according to the actual project needs will become more complex, where things can be processed by Redis.
The code for this section has been submitted to Github(Github.com/xcbeyond/mi…), if necessary.