Spring Boot 2 WebFlux integrates Redis

Posted by JeditL on Fri, 17 Dec 2021 09:53:00 +0100

This is the original Article 106 of the mason

Article project:

  • JDK 1.8
  • Maven 3.5.2
  • Spring Boot 2.1.3.RELEASE
  • Project Name: springboot-weblux-6-redis
  • Project address: see the end of the document

preface

In the previous lecture, we talked about how to integrate MongoDB. Here we continue to talk about how to operate Redis as a data source. So what is IDS?

Redis is a high-performance key value database. GitHub address: https://github.com/antirez/redis . GitHub describes it this way:

Redis is an in-memory database that persists on disk. The data model is key-value, but many different kind of values are supported: Strings, Lists, Sets, Sorted Sets, Hashes, HyperLogLogs, Bitmaps.

Redis is an in memory database stored on disk. There are many supported data types: strings, lists, sets, sorted sets, hashes, hyperlogs, bitmaps, etc.

Easy installation tutorial (for Mac/Linux)

Download and unzip

Download installation package redis-x.x.x.tar.gz
 
## decompression
 
tar zxvf redis-2.8.17.tar.gz
 

Compile and install

cd redis-x.x.x/
 
make ## compile
 

Start Redis

cd src/
 
redis-server
 

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

structure

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

The core of the directory is as follows

  • pom.xml maven configuration
  • application.properties configuration file
  • domain entity class
  • controller control layer, key points of this paper

Add POM dependency and configuration

In POM XML configuration new dependencies:

 <!-- Spring Boot Responsive Redis rely on -->
 
 <dependency>
 
 <groupId>org.springframework.boot</groupId>
 
 <artifactId>spring-boot-starter-data-redis-reactive</artifactId>
 
 </dependency>
 

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

## Redis configuration
 
## Redis server address
 
spring.redis.host=127.0.0.1
 
## Redis server connection port
 
spring.redis.port=6379
 
## Redis server connection password (blank by default)
 
spring.redis.password=
 
# Connection timeout (MS)
 
spring.redis.timeout=5000
 

The default password is empty. Note that the connection timeout cannot be too small or 0, otherwise an exception RedisCommandTimeoutException:Commandtimedout will be caused.

object

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

import org.springframework.data.annotation.Id;
 


 
import java.io.Serializable;
 


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


 
 private static final long serialVersionUID = -2081742442561524068L;
 


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


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


 
 /**
 
     * City name
 
     */
 
 private String cityName;
 


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

Notable points:

  • @The Id annotation marks the primary key or unique identifier of the corresponding library table. Because this is our DO, the data access objects are mapped to the data store one by one.
  • City must implement serialization because it needs to serialize the objects and store them in Redis. If Serializable is not implemented, an exception will be raised: Java lang.IllegalArgumentException:DefaultSerializerrequires aSerializablepayload but received anobjectof type
  • If you do not use the default serialization, you need to customize the serialization implementation. Just implement the RedisSerializer interface, and then use redistemplate Setvalueserializer method to set the serialization implementation of your implementation. Support JSON, XML, etc.

Control layer CityWebFluxController

The code is as follows:

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<City> 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<City> 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<Long> 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));
 
 }
 
}
 

Code explanation

  • Inject RedisTemplate object with @ Autowired. This object is very similar to the function of Spring's JdbcTemplate. RedisTemplate encapsulates RedisConnection and has the functions of connection management, serialization and various operations. There is also a support object for String, StringRedisTemplate.
  • To delete an object in Redis, directly call delete(key) through the key value.
  • The Redis operation view interface class uses ValueOperations, which corresponds to Redis String/Value operations. Get is to get data; Set is the inserted data, and the expiration time can be set. The failure time set here is 60 s.
  • There are other operation views, ListOperations, SetOperations, ZSetOperations, and HashOperations.

Operation engineering

An operation Redis project is developed. Now run the project for verification. Use the toolbar on the right side of IDEA, click Maven Project Tab, and click the install command of Maven plug-in. Or use the command line to execute the Maven cleaning and installation instructions under the project root directory:

cd springboot-webflux-6-redis
 
mvn clean install
 

See the successful output in the console:

... ellipsis
 
[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 the Application class startup in the IDEA, any normal mode or Debug mode. You can see the output of successful operation on the console:

... ellipsis
 
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

Get city information http://127.0.0.1:8080/city/2

If you wait for 60s, you will get null again. Because the expiration time is set to 60 s when saving.

summary

Here, we discussed how Spring WebFlux integrates Redis. Describes how to operate Redis through RedisTemplate. Because Redis has excellent performance in obtaining resources, Redis is often used as a cache storage object. Next, we use IDs to implement cache operation.

Code GiHub: https://github.com/JeffLi1993/springboot-learning-example

Series tutorial directory

  • 01: WebFlux series tutorial outline
  • 02: WebFlux quick start practice
  • 03: WebFlux Web CRUD practice
  • 04: WebFlux integration Mongodb
  • 05: WebFlux integrates Thymeleaf
  • 06: Thymeleaf and Mongodb practices in WebFlux
  • 07: WebFlux integrates Redis
  • 08: Redis cache in WebFlux
  • 09: WebSocket communication in WebFlux
  • 10: WebFlux integration test and deployment
  • 11: WebFlux practical library management system

Code example

The example readers of this article can view the module project name in the following warehouse: 2-x-spring-boot-weblux-handling-errors:

  • Github: https://github.com/JeffLi1993/springboot-learning-example
  • Gitee: https://gitee.com/jeff1993/springboot-learning-example

If you are interested in these, you are welcome to support star, follow, collect and forward!

reference material

  • Spring Boot 2.x WebFlux series: https://www.bysocket.com/archives/2290
  • spring.io official documents