Table of Contents
1. Use Spring Initializr to create project web projects
Home Database Redis Detailed tutorial on integrating the Redis framework to build SpringBoot2.X

Detailed tutorial on integrating the Redis framework to build SpringBoot2.X

Dec 08, 2020 pm 05:46 PM

redis database tutorial Column introduces the tutorial of building SpringBoot2.X from scratch

Detailed tutorial on integrating the Redis framework to build SpringBoot2.X

Recommended (free): redis database tutorial

I don’t know what to write recently. I have written an article about Kafka integrating Springboot before. Everyone’s response is quite enthusiastic. Hehehe, I feel that it helps everyone. It's pretty good, and it can be considered that I have achieved my goal. It just so happens that today's business module is springboot integrating redis. Because I have done it before, I have ready-made code. It can be used after cv, so I have more time, so I will give it to you. Let’s sort out the code implementation of Springboot’s integration of Redis. From project construction to source code implementation, everything is included below. Read it patiently. I believe it will be helpful to you.

Okay, without further ado, let’s get started. Well, similarly, it is still recommended to implement it on your own PC.
Personal public account: Java Architect Alliance, daily updated technical articles

1. Use Spring Initializr to create project web projects

1. File→New→Project

2. Click Next as shown in the picture and name the Group and Artifact

3. After Next, as shown in the figure, check the required dependencies, and Spring Initializr will automatically import the required starter

4. After the project is successfully created , the dependencies in the pom.xml file are as follows


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.2.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.heny</groupId>
	<artifactId>spring-boot-redis</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>spring-boot-redis</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.1.1</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

5. Add the redis starter


<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-data-redis</artifactId>
	</dependency>
in the pom.xml file

6. Create JavaBean to encapsulate database data and need to implement Serializable


package com.henya.springboot.bean;

import java.io.Serializable;

public class Employee implements Serializable{
	
	private Integer id;
	private String lastName;
	private String email;
	private Integer gender; //性别 1男 0女
	private Integer dId;
	
	
	public Employee() {
		super();
	}

	
	public Employee(Integer id, String lastName, String email, Integer gender, Integer dId) {
		super();
		this.id = id;
		this.lastName = lastName;
		this.email = email;
		this.gender = gender;
		this.dId = dId;
	}
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public Integer getGender() {
		return gender;
	}
	public void setGender(Integer gender) {
		this.gender = gender;
	}
	public Integer getdId() {
		return dId;
	}
	public void setdId(Integer dId) {
		this.dId = dId;
	}
	@Override
	public String toString() {
		return "Employee [id=" + id + ", lastName=" + lastName + ", email=" + email + ", gender=" + gender + ", dId="
				+ dId + "]";
	}
}

Note:
You need to implement the Serializable interface when writing JavaBean objects, otherwise the following will be reported Error:

Cannot deserialize; nested exception is org.springframework.core.serializer.support.SerializationFailedException

7. Integrate Mybatis operation database, in the application.properties configuration file Configure data source information in


#serverTimezone用于指定时区,不然会报错
spring.datasource.url=jdbc:mysql://localhost:3306/cache?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456

# 开启驼峰命名法规则
mybatis.configuration.map-underscore-to-camel-case=true
#日志级别
logging.level.com.henya.springboot.mapper=debug

8. Use the annotated version of Mybatis to create Mapper


##

package com.henya.springboot.mapper;


import com.henya.springboot.bean.Employee;
import org.apache.ibatis.annotations.*;

@Mapper
public interface EmployeeMapper {

 @Select("SELECT * FROM employee WHERE id=#{id}")
 public Employee getEmpById(Integer id);

 @Update("UPDATE employee SET lastName=#{lastName},email=#{email},gender=#{gender},d_id=#{dId} WHERE id=#{id}")
 public void updateEmp(Employee employee);

 @Delete("DELETE FROM emlpoyee WHERE id=#{id}")
 public void delEmpById(Integer id);

 @Insert("INSERT INTO employee(lastName, email, gender, d_id) VALUES (#{lastName}, #{email}, #{gender}, #{dId})")
 public Employee insertEmp(Employee employee);

 @Select("SELECT * FROM employee WHERE lastName=#{lastName}")
 public Employee getEmpByLastName(String lastName);
}

Note:

You need to use the @MapperScan annotation to scan the interface where the Mapper is located. You only need to add it to the main program class. In addition, use @EnableCaching to enable caching.


@MapperScan("com.henya.springboot.mapper")
@SpringBootApplication
@EnableCaching //开启缓存
public class SpringBootRedisApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootRedisApplication.class, args);
	}
}

9. Write the Service class for accessing the database or redis cache


package com.henya.springboot.service;
import com.henya.springboot.bean.Employee;
import com.henya.springboot.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.*;
import org.springframework.stereotype.Service;

@CacheConfig(cacheNames = "emp") //抽取缓存的公共配置
@Service
public class EmployeeService {
 @Autowired
 EmployeeMapper employeeMapper;

 /**
 * @param id
 * @return
 */
 @Cacheable(cacheNames = {"emp"},keyGenerator = "myKeyGenerator")
 public Employee getEmpById(Integer id) {
 System.err.println("开始查询"+ id +"号员工");
 Employee employee = employeeMapper.getEmpById(id);
 return employee;
 }

 /**
 * @CachePut:既调用方法(这个方法必须要执行),又更新缓存数据
 * @param employee
 * @return
 */
 @CachePut(value = "emp",key = "#result.id")
 public Employee updateEmp(Employee employee){
 System.err.println("开始更新" + employee.getId() + "号员工");
 employeeMapper.updateEmp(employee);
 return employee;
 }

 /**
 * @CacheEvict:缓存清除
 * @param id
 */
 @CacheEvict(value = "emp",beforeInvocation = true)
 public void deleteEmp(Integer id){
 System.err.println("删除" + id + "员工");
 int i = 10/0;
 }

10. Write the Controller class


package com.henya.springboot.controller;


import com.henya.springboot.bean.Employee;
import com.henya.springboot.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description:
 * @Author:HenYa
 * @CreatTime:2019/12/1 12:44
 */
@RestController
public class EmployeeController {
 @Autowired
 EmployeeService employeeService;

 @GetMapping("/emp/{id}")
 public Employee getEmpById(@PathVariable("id") Integer id){
 Employee employee = employeeService.getEmpById(id);
 return employee;
 }

 @GetMapping("/emp")
 public Employee updateEmp(Employee employee){
 Employee emp = employeeService.updateEmp(employee);
 return emp;
 }
}

2. Test whether SpringBoot integrates Redis successfully

1. Access in the browser, you can also use the test class. The author used the browser to access http ://localhost:8080/emp/1 for testing. When accessing for the first time, the console will prompt to start querying employee No. 1, as shown in the figure.

#2. When accessing again, there is no sql log in the console, as shown in the figure.

3. At this time, there is data when using the RedisDesktopManager tool to view redis, and the cacheName is emp, as shown in the figure

Only the emp object is serialized. Looking at the source code, we can see that Redis uses Jdk for serialization by default.


static RedisSerializer<Object> java(@Nullable ClassLoader classLoader) {
 return new JdkSerializationRedisSerializer(classLoader);
 }

Check out the following implementations of the RedisSerializer interface:

What we commonly use is in json format Serialization. But you need to customize RedisCacheManager.

3. Customize RedisCacheManager


package com.henya.springboot.config;
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.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * @Description:
 * @Author:HenYa
 * @CreatTime:2019/12/6 20:50
 */
@Configuration
public class MyRedisConfig {
 @Bean
 public RedisCacheManager empCacheManager(RedisConnectionFactory redisConnectionFactory){
 //RedisCacheManager redisCacheManager = new RedisCacheManager(redisConnectionFactory);
 RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);

 RedisSerializer<Object> redisSerializer = new GenericJackson2JsonRedisSerializer();

 RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer);
 RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(pair);
 // 默认会将CacheName作为key的前缀
 return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);
 }
 }
At this time, the cached data in Redis is serialized in Json format, as shown in the figure.

The above is the detailed content of Detailed tutorial on integrating the Redis framework to build SpringBoot2.X. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do you stay updated with the latest features and best practices for Redis? How do you stay updated with the latest features and best practices for Redis? Aug 20, 2025 pm 02:58 PM

Maintaining knowledge of Redis’s latest features and best practices is the key to continuous learning and focus on official and community resources. 1. Regularly check Redis official website, document updates and ReleaseNotes, subscribe to the GitHub repository or mailing list, get version update notifications and read the upgrade guide. 2. Participate in technical discussions on Redis's Google Groups mailing list, Reddit sub-section, StackOverflow and other platforms to understand other people's experience and problem solutions. 3. Build a local testing environment or use Docker to deploy different versions for functional testing, integrate the Redis upgrade test process in CI/CD, and master the value of feature through actual operations. 4. Close

How to rename a key safely using RENAME and RENAMENX? How to rename a key safely using RENAME and RENAMENX? Aug 21, 2025 am 01:03 AM

To safely rename the Redis key, use RENAMENX should be preferred. RENAME will directly rename and overwrite the existing target key, which poses a risk of data loss; RENAMENX will only perform renaming when the target key does not exist, and returning 0 means failure; it is recommended to check whether the target key exists before operation, use RENAMENX in the production environment, combine Lua scripts to ensure atomicity, and backup original data to ensure security.

What is the 'score' in a Sorted Set? What is the 'score' in a Sorted Set? Aug 11, 2025 am 11:55 AM

ThescoreinaRedisSortedSetisanumericalvaluethatdeterminestheelement'spositionwithintheset.Unlikeregularsets,whichareunordered,SortedSetsusescorestomaintainanautomaticorderfromsmallesttolargest.Eachmemberisassociatedwithascore,enablingdynamicrankingand

How to troubleshoot a Redis instance that is consuming too much CPU? How to troubleshoot a Redis instance that is consuming too much CPU? Aug 14, 2025 am 11:18 AM

HighCPUusageinRedisistypicallycausedbyinefficientqueries,excessiveclienttraffic,memorypressure,ormisconfigurations.Toaddressthis,first,checkforlargeorcomplexcommandslikeKEYS*,SMEMBERS,orLRANGEonbigdatasetsandreplacethemwithsaferalternativessuchasSCAN

What is the difference between ZRANGE and ZREVRANGE? What is the difference between ZRANGE and ZREVRANGE? Aug 04, 2025 am 01:05 AM

ZRANGEretrieveselementsinascendingscoreorder,whileZREVRANGEreturnsthemindescendingorder.WhenworkingwithRedissortedsets,useZRANGEtogetthelowest-to-highestscores—idealforbottom-rankedentriesornaturalorderlistings—andZREVRANGEfortop-rankeditems,suchasst

What is the GETDEL command introduced in Redis 6.2? What is the GETDEL command introduced in Redis 6.2? Aug 29, 2025 am 07:35 AM

GETDEL was introduced in Redis 6.2 to atomically obtain and delete string keys. 1. It combines the GET and DEL that originally required two operations into one to avoid concurrent interference; 2. Return the value and delete it if the key exists, otherwise it returns nil; 3. Applicable to scenes such as one-time tokens, light queues, and deletion after fetching; 4. Only support string types, efficient operation and atomicity, and is suitable for use in high-concurrency environments.

What are the common use cases for the String data type in Redis? What are the common use cases for the String data type in Redis? Aug 16, 2025 am 08:59 AM

Redis strings are widely used and are suitable for a variety of scenarios. 1. Can be used to cache static or computed data, such as API response, HTML fragments and database query results, store and obtain through SET and GET commands, and set expiration time with EX parameters to improve application performance and reduce database load; 2. Support atomic operations, suitable for use as speed limit and temporary counters, such as tracking login attempts, API call frequency, etc., and use INCR, DECR and other commands to avoid concurrency problems; 3. Suitable as a session storage solution for web applications, save serialized session data in the form of a string, supports fast read and write and automatic expiration, and is suitable for distributed architectures; 4. It can be used as a functional switch or a simple configuration item to dynamically control application behavior, such as

What are the key metrics to monitor for a healthy Redis instance? What are the key metrics to monitor for a healthy Redis instance? Aug 29, 2025 am 06:38 AM

TokeepaRedisinstancehealthy,monitorkeymetricsinthefollowingorder:1.Memoryusage,trackingused_memoryandused_memory_rsswhileapproachingsystemRAMlimits,andmanagingitviamaxmemory,evictionpolicies,efficientdatastructures,andcompression;2.CPUutilization,mon

See all articles