服务器之家:专注于服务器技术及软件下载分享
分类导航

Mysql|Sql Server|Oracle|Redis|MongoDB|PostgreSQL|Sqlite|DB2|mariadb|Access|数据库技术|

服务器之家 - 数据库 - Redis - 从零搭建SpringBoot2.X整合Redis框架的详细教程

从零搭建SpringBoot2.X整合Redis框架的详细教程

2021-01-07 17:10Java爱coding Redis

这篇文章主要介绍了从零搭建SpringBoot2.X整合Redis框架的详细教程,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

最近也不知道写啥,看之前写过Kafka整合Springboot的文章,大家反响还挺热烈的,嘿嘿嘿,就感觉帮助到大家了还挺好的,也算是达到了自己的目的,正好,今天业务模块是springboot整合redis,因为之前做过,所以有现成的代码,cv一下之后就可以了,所以时间比较多,那就给大家整理一下Springboot整合Redis的代码实现吧,从项目搭建到源码实现,下面全都有,耐心看完,相信会对你有所帮助的

好了,话不多说,我们开始吧,同样的,还是建议能够自己在自己的PC端实现一下
个人公众号:Java架构师联盟,每日更新技术好文

 

一、使用Spring Initializr创建项目web项目

 

1、File→New→Project

从零搭建SpringBoot2.X整合Redis框架的详细教程

2、点击Next如图所示,命名好Group和Artifact

从零搭建SpringBoot2.X整合Redis框架的详细教程

3、Next后如图所示,勾选中需要的依赖,Spring Initializr会自动导入所需的starter

从零搭建SpringBoot2.X整合Redis框架的详细教程

4、创建项目成功后,pom.xml文件中的依赖如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?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、在pom.xml文件中添加redis的starter

?
1
2
3
4
<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>

6、创建JavaBean用于封装数据库数据,需要实现Serializable

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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 + "]";
    }
}

注意:
在写JavaBean对象时需要实现Serializable接口否则会报以下错误:

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

7、整合Mybatis操作数据库,在application.properties配置文件中配置数据源信息

?
1
2
3
4
5
6
7
8
9
#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、使用注解版Mybatis创建Mapper

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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);
}

注意:
需要使用使用@MapperScan注解扫描Mapper所在的接口,只需要加在主程序类上即可。除此之外,还要使用@EnableCaching用于开启缓存。

?
1
2
3
4
5
6
7
8
9
@MapperScan("com.henya.springboot.mapper")
@SpringBootApplication
@EnableCaching //开启缓存
public class SpringBootRedisApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(SpringBootRedisApplication.class, args);
    }
}

9、编写Service类,用于访问数据库或redis缓存

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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、编写Controller类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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;
 }
}

 

二、测试SpringBoot整合Redis是否成功

 

1、在浏览器访问,也可以使用测试类,笔者使用了浏览器访问http://localhost:8080/emp/1进行测试,初次访问时,控制台会提示开始查询1号员工,如图所示。

从零搭建SpringBoot2.X整合Redis框架的详细教程

2、再次访问时,控制台并没有sql日志,如图所示。

从零搭建SpringBoot2.X整合Redis框架的详细教程

3、此时使用RedisDesktopManager工具查看redis时有数据,并且cacheName为emp,如图所示

从零搭建SpringBoot2.X整合Redis框架的详细教程

只是emp对象被序列化了。查看源码可知Redis默认使用Jdk进行序列化。

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

查看RedisSerializer接口的实现有以下几种:

从零搭建SpringBoot2.X整合Redis框架的详细教程

我们常用的就是以json的格式进行序列化。但是需要自定义RedisCacheManager。

 

三、自定义RedisCacheManager

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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);
 }
 }

此时,Redis中缓存数据就以Json的格式进行序列化,如图所示。

从零搭建SpringBoot2.X整合Redis框架的详细教程

到此这篇关于从零搭建SpringBoot2.X整合Redis框架的详细教程的文章就介绍到这了,更多相关SpringBoot2.X整合Redis框架内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.cnblogs.com/biwz/archive/2020/12/08/14102204.html

延伸 · 阅读

精彩推荐
  • RedisLinux Redis 的安装步骤详解

    Linux Redis 的安装步骤详解

    这篇文章主要介绍了 Linux Redis 的安装步骤详解的相关资料,希望大家通过本文能掌握如何安装Redis,需要的朋友可以参考下 ...

    carl-zhao3822019-11-08
  • Redis就这?Redis持久化策略——AOF

    就这?Redis持久化策略——AOF

    今天为大家介绍Redis的另一种持久化策略——AOF。注意:AOF文件只会记录Redis的写操作命令,因为读命令对数据的恢复没有任何意义...

    头发茂密的刘叔4052021-12-14
  • RedisRedis数据结构之链表与字典的使用

    Redis数据结构之链表与字典的使用

    这篇文章主要介绍了Redis数据结构之链表与字典的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友...

    白泽来了4052021-08-03
  • RedisRedis分布式锁升级版RedLock及SpringBoot实现方法

    Redis分布式锁升级版RedLock及SpringBoot实现方法

    这篇文章主要介绍了Redis分布式锁升级版RedLock及SpringBoot实现,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以...

    等不到的口琴7802021-07-25
  • Redis在ssm项目中使用redis缓存查询数据的方法

    在ssm项目中使用redis缓存查询数据的方法

    本文主要简单的使用Java代码进行redis缓存,即在查询的时候先在service层从redis缓存中获取数据。如果大家对在ssm项目中使用redis缓存查询数据的相关知识感...

    caychen8962019-11-12
  • RedisRedis存取序列化与反序列化性能问题详解

    Redis存取序列化与反序列化性能问题详解

    这篇文章主要给大家介绍了关于Redis存取序列化与反序列化性能问题的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参...

    这名字已经存在9742021-02-24
  • Redis聊一聊Redis与MySQL双写一致性如何保证

    聊一聊Redis与MySQL双写一致性如何保证

    一致性就是数据保持一致,在分布式系统中,可以理解为多个节点中数据的值是一致的。本文给大家分享Redis与MySQL双写一致性该如何保证,感兴趣的朋友一...

    mind_programmonkey6432021-08-12
  • Redisredis启动,停止,及端口占用处理方法

    redis启动,停止,及端口占用处理方法

    今天小编就为大家分享一篇redis启动,停止,及端口占用处理方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧 ...

    澄海单挑狂5152019-11-14