Home > Database > Redis > body text

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

coldplay.xixi
Release: 2020-12-08 17:46:43
forward
3185 people have browsed it

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>
Copy after login

5. Add the redis starter


<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-data-redis</artifactId>
	</dependency>
Copy after login
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 + "]";
	}
}
Copy after login

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
Copy after login

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);
}
Copy after login

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);
	}
}
Copy after login

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;
 }
Copy after login

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;
 }
}
Copy after login

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);
 }
Copy after login

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);
 }
 }
Copy after login
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!

Related labels:
source:jb51.net
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template