This is the 14th day of my participation in the First Challenge 2022

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 The Github website and download the latest Windows X64 zip as shown in the following image:

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:

# redis configuration
#Redis server address
Spring. Redis. Host = 127.0.0.1
#Redis server connection port
spring.redis.port=6379
#Redis database index (default 0)
spring.redis.database=0  
# maximum number of connections in the pool (use negative values to indicate no limit)
spring.redis.jedis.pool.max-active=50
Maximum connection pool blocking wait time (negative value indicates no limit)
spring.redis.jedis.pool.max-wait=3000
The maximum number of free connections in the connection pool
spring.redis.jedis.pool.max-idle=20
Minimum free connection in connection pool
spring.redis.jedis.pool.min-idle=2
Connection timeout (ms)
spring.redis.timeout=5000
Copy 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) *@authorXcbeyond * July 19, 2018 2:56:24 PM */
@Component
public class RedisUtils {

	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	/** * read cache **@param key
	 * @return* /
	public String get(final String key) {
		return redisTemplate.opsForValue().get(key);
	}

	/** * write cache */
	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;
	}

	/** * update the cache */
	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();
		}
		returnresult; }}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;
/ * * * *@authorXcbeyond * July 19, 2018 3:08:04 PM */

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class RedisTest {
	@Resource
	private RedisUtils redisUtils;

	/** * Insert cached data */
	@Test
	public void set(a) {
		redisUtils.set("redis_key"."redis_vale");
	}
	
	/** * Read the cached data */
	@Test
	public void get(a) {
		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 of this chapter has been submitted to Github(Micro-service/Springboot at Master · xcBeyond/Micro-service · Github). If necessary, download it yourself.