How to integrate Redis through WebFlux, Spring Boot 2

Redis is an in-memory database, stored on disk. There are many data types supported: Strings, Lists, Sets, Sorted Sets, Hashes, HyperLogLogs, Bitmaps, etc.

Simple installation tutorial (for Mac/ Linux )

Download and unzip

Download the installation package redis-xxxtar.gz

tar zxvf redis-2.8.17.tar.gz

Compile and install

cd redis-xxx /
make

Start Redis

cd src
redis-server

If you need to run in the daemon process, set daemonize from no to yes, and specify to run: redis-server redis.conf

How to integrate Redis through WebFlux, Spring Boot 2 How to integrate Redis through WebFlux, Spring Boot 2

structure

Similar to the project construction mentioned above, create a new project to write this case. The project is shown in the figure:

How to integrate Redis through WebFlux, Spring Boot 2 How to integrate Redis through WebFlux, Spring Boot 2

The core of the directory is as follows

pom.xml maven configuration

application.properties configuration file

domain entity class

controller control layer, the main points of this article

New POM dependency and configuration

Configure new dependencies in pom.xml:

 
org.springframework.boot
spring-boot-starter-data-redis-reactive

Similar to MongoDB configuration, configure the connection to Redis in application.properties:

## Redis configuration

## Redis server address

spring.redis.host=127.0.0.1

## Redis server connection port

spring.redis.port=6379

## Redis server connection password (empty by default)

spring.redis.password=

# Connection timeout period (milliseconds)
spring.redis.timeout=5000

The default password is empty. Note here that the connection timeout time cannot be too small or 0, otherwise it will cause an exception RedisCommandTimeoutException: Command timed out.

Object

Modify the city entity object class in the org.spring.springboot.domain package. City (City) object City, the code is as follows:

import org.springframework.data.annotation.Id;

import java.io.Serializable;

/**
* City entity
*
*/
public class City implements Serializable {

private static final long serialVersionUID = -2081742442561524068L;

/**
* City code
*/
@Id
private Long id;

/**
* Province number
*/
private Long provinceId;

/**
* city name
*/
private String cityName;

/**
* Description
*/
private String description;

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public Long getProvinceId() {
return provinceId;
}

public void setProvinceId(Long provinceId) {
this.provinceId = provinceId;
}

public String getCityName() {
return cityName;
}

public void setCityName(String cityName) {
this.cityName = cityName;
}

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}
}

Points worth noting:

The @Id annotation marks the primary key or unique identifier of the corresponding library table. Because this is our DO, data access objects are mapped to data storage one by one.

City must be serialized because the object needs to be serialized and stored in Redis. If Serializable is not implemented, an exception will be raised: java.lang.IllegalArgumentException: DefaultSerializer requires a Serializable payload but received an object of type

If you are not using the default serialization, you need to customize the serialization implementation, just implement the RedisSerializer interface to implement it, and then use the RedisTemplate.setValueSerializer method to set the serialization implementation you implemented. Support JSON, XML, etc.

Control layer CityWebFluxController

code show as below:

import org.spring.springboot.domain.City;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping(value = "/city")
public class CityWebFluxController {

@Autowired
private RedisTemplate redisTemplate;

@GetMapping(value = "/{id}")
public Mono findCityById(@PathVariable("id") Long id) {
String key = "city_" + id;
ValueOperations<String, City> operations = redisTemplate.opsForValue();
boolean hasKey = redisTemplate.hasKey(key);
City city = operations.get(key);

if (!hasKey) {
return Mono.create(monoSink -> monoSink.success(null));
}
return Mono.create(monoSink -> monoSink.success(city));
}

@PostMapping()
public Mono saveCity(@RequestBody City city) {
String key = "city_" + city.getId();
ValueOperations<String, City> operations = redisTemplate.opsForValue();
operations.set(key, city, 60, TimeUnit.SECONDS);

return Mono.create(monoSink -> monoSink.success(city));
}

@DeleteMapping(value = "/{id}")
public Mono deleteCity(@PathVariable("id") Long id) {
String key = "city_" + id;
boolean hasKey = redisTemplate.hasKey(key);
if (hasKey) {
redisTemplate.delete(key);
}
return Mono.create(monoSink -> monoSink.success(id));
}
}

Use @Autowired to inject RedisTemplate objects. This object is very similar to Spring's JdbcTemplate. RedisTemplate encapsulates RedisConnection and has connection management, serialization, and various operations. There is also StringRedisTemplate, a support object for String.

To delete an object in Redis, call delete(key) directly through the key value.

The Redis operation view interface class uses ValueOperations, which corresponds to Redis String/Value operations. get is to obtain data; set is to insert data, and the expiration time can be set. The expiration time set here is 60 s.

There are other operation views, ListOperations, SetOperations, ZSetOperations and HashOperations.

Run the project

An operational Redis project has been developed. Run the project below to verify it. Use the toolbar on the right side of IDEA, click Maven Project Tab, and click the install command of the Maven plug-in to use  . Or use the form of command line, in the root directory of the project, execute the instructions of Maven to clean and install the project:

cd springboot-webflux-6-redis
mvn clean install

See successful output in the console:

... omitted
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:30 min
[INFO] Finished at: 2018-10-15T10:00:54+08:00
[INFO] Final Memory: 31M/174M
[INFO] ------------------------------------------------------------------------
Execute Application class startup in IDEA, any normal mode or Debug mode. You can see the output of a successful run in the console:

... omitted
2018-04-10 08:43:39.932 INFO 2052 --- [ctor-http-nio-1] r.ipc.netty.tcp.BlockingNettyContext : Started HttpServer on /0:0:0:0:0:0:0:0:8080
2018-04-10 08:43:39.935 INFO 2052 --- [ main] o.s.b.web.embedded.netty.NettyWebServer : Netty started on port(s): 8080
2018-04-10 08:43:39.960 INFO 2052 --- [ main] org.spring.springboot.Application : Started Application in 6.547 seconds (JVM running for 9.851)

Open the POST MAN tool, which is necessary for development. Do the following:

New city information POST http://127.0.0.1:8080/city
How to integrate Redis through WebFlux, Spring Boot 2 How to integrate Redis through WebFlux, Spring Boot 2

Get city information GET http://127.0.0.1:8080/city/2
How to integrate Redis through WebFlux, Spring Boot 2 How to integrate Redis through WebFlux, Spring Boot 2

If you wait 60s later, it will get empty again. Because the expiration time is set to 60 s when saving.

to sum up

Here, how to integrate Redis with Spring WebFlux is discussed. Introduced how to operate Redis through RedisTemplate. Because Redis has excellent performance in acquiring resources, Redis is often used as a cache storage object. Below we use Reids to implement the cache operation.

This article address: https://www.linuxprobe.com/redis-spring-boot.html

Guess you like

Origin blog.csdn.net/u014389734/article/details/108233520