Spring Boot integrates NoSQL database Redis

insert image description here

?? Column recommendation: Spring Boot integrates third-party components
?? Series of articles: [Quick Start] Use SpringBoot 2.X + Mybatis-Plus to easily implement CRUD (continuously updated...)
?? Column introduction:
In daily practical development , we will use the enterprise-level rapid construction project framework Spring Boot to integrate and develop various components. This column will summarize the detailed steps of using Spring Boot to integrate with commonly used third-party components. Welcome to exchange and learn. ???

Article directory

In daily development, in addition to using Spring Bootthis enterprise-level framework for quickly building projects, with the substantial increase in the amount of business data, the pressure on the metadata database has increased exponentially. In this context, Redisthis NoSQLdatabase is already an indispensable part of the entire project architecture. Knowing how to Spring Bootintegrate Redisis a necessary skill for developers today. Next, the integration steps will be described in detail.

1. Environmental preparation

Before starting development, we need to prepare some environment configurations:

  • jdk 1.8 or other higher version
  • Development tools IDEA
  • Manage dependencies Maven
  • Redis environment, it is recommended to build a redis environment in the linux system

2. Build the Spring Boot project

Open idea -> file -> Nwe -> Project, as shown in the figure, check and fill in the relevant configuration information:

insert image description here

Check some initial dependent configurations:

insert image description here

The Spring Boot project initialization is complete.

insert image description here

3. Introduce Redis dependency

After building the Spring Boot project, you need to pom.xmlintroduce redisrelated dependencies in the file

<!-- redis -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

<!-- spring2.X集成redis所需common-pool2-->
<dependency>
	<groupId>org.apache.commons</groupId>
	<artifactId>commons-pool2</artifactId>
	<version>2.6.0</version>
</dependency>

insert image description here

Four, Reds related configuration

After introducing redis-related dependencies into the project, you need to configure redis, and application.propertiesconfigure redis:

# Redis服务器地址
spring.redis.host=自己搭建的redis服务器的 IP
# Redis服务器连接端口
spring.redis.port=6379
# Redis数据库索引(默认为0)
spring.redis.database= 0
# 连接超时时间(毫秒)
spring.redis.timeout=1800000
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.lettuce.pool.max-active=20
# 最大阻塞等待时间(负数表示没限制)
spring.redis.lettuce.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.lettuce.pool.max-idle=5
# 连接池中的最小空闲连接
spring.redis.lettuce.pool.min-idle=0

insert image description here

5. Add Redis configuration class

After completing the relevant configuration of Redis, add the Redis configuration class (ready to use):

package com.zhao.demo.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

/**
 * @author xiaoZhao
 * @date 2022/9/6
 * @describe
 */
@EnableCaching
@Configuration
public class RedisConfig extends CachingConfigurerSupport {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setConnectionFactory(factory);
        //key序列化方式
        template.setKeySerializer(redisSerializer);
        //value序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //value hashmap序列化
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        return template;
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        //解决查询缓存转换异常的问题
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        // 配置序列化(解决乱码的问题),过期时间600秒
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(600))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .disableCachingNullValues();
        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }
}

insert image description here

Six, test it

After all the environment dependencies and configurations are built, test it.

① First, make sure that the installed Redisserver has started the Redis service

insert image description here

② To write controllera class, the premise needs to introduce Spring Boot Webthe dependency of :

insert image description here

package com.zhao.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author xiaoZhao
 * @date 2022/9/6
 * @describe
 */
@RestController
@RequestMapping("/redistest")
public class RedisTestController {

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping
    public String testRedis(){
        // 设置值到reids
        redisTemplate.opsForValue().set("name","jack");
        // 从redis中获取值
        String name = (String)redisTemplate.opsForValue().get("name");
        return name;
    }
}

③ Start the Spring Boot project and send a request to the interface on the browser:

insert image description here

The project starts successfully, and /redistesta request is sent to the interface

insert image description here

The request is sent successfully, the data is obtained, and the test is successful. So far, all the steps of integrating Redis with Spring Boot have been completed.

insert image description here

at last

I know that most junior and middle-level Java engineers want to improve their skills, and they often try to grow by themselves or enroll in classes. However, the tuition fees of nearly 10,000 yuan for training institutions are really stressful. The effect of self-study is inefficient and long, and it is easy to hit the ceiling and stagnate in technology!

Therefore, I collected and sorted out a " Complete Set of Learning Materials for Java Development " and gave it to everyone. The original intention is also very simple, that is, I hope to help friends who want to learn and improve themselves but don't know where to start, and at the same time reduce everyone's burden.

The editor has encrypted: aHR0cHM6Ly9kb2NzLnFxLmNvbS9kb2MvRFVrVm9aSGxQZUVsTlkwUnc==For security reasons, we have encoded the website through base64, and you can decode the URL through base64.

Guess you like

Origin blog.csdn.net/m0_67265464/article/details/126774105