Spring Boot从入门到精通(六)集成Redis实现缓存机制

来源:素文宅博客

地址:https://blog.yoodb.com/yoodb/article/detail/1570

Redis(Remote Dictionary Server ),即远程字典服务,是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。

Redis是一个高性能的key-value内存数据库,通常被称为数据结构服务器,因为值可以是字符串、哈希、列表、集合和有序集合等类型,在如今系统不断追求高并发、高效率的大环境下,Redis被广泛使用。

本文在前一篇“Spring Boot从入门到精通(四)连接MySQL数据库(附源码)”文章中的项目源码基础上(关注“Java精选”微信公众号,切换至后台->聚合->开源项目,可以查看Spring Boot系列框架从入门到精通教程)。

通过查询MySQL数据库中表数据存储到Redis缓存中,之后再使用Redis查询数据返回参数呈现到浏览器上,利用Spring Boot框架集成Redis实现缓存机制,分享给大家参考和学习。

 

  Maven项目pom.xml文件

在Spring Boot项目中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

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

<?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.3.0.M2</version>

        <relativePath/> <!-- lookup parent from repository -->

    </parent>

    <groupId>com.yoodb</groupId>

    <artifactId>springboot-study-demo04</artifactId>

    <version>0.0.1-SNAPSHOT</version>

    <packaging>war</packaging>

    <name>springboot-study-demo04</name>

    <description>Demo project for Spring Boot</description>

 

    <properties>

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

    </properties>

 

    <dependencies>

        <dependency>

            <groupId>org.mybatis.spring.boot</groupId>

            <artifactId>mybatis-spring-boot-starter</artifactId>

            <version>1.0.0</version>

        </dependency>

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-data-redis</artifactId>

        </dependency>

        <dependency>

            <groupId>mysql</groupId>

            <artifactId>mysql-connector-java</artifactId>

        </dependency>

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-jdbc</artifactId>

        </dependency>

 

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-web</artifactId>

        </dependency>

 

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-tomcat</artifactId>

            <scope>provided</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>

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-jdbc</artifactId>

        </dependency>

        <dependency>

            <groupId>org.xmlunit</groupId>

            <artifactId>xmlunit-core</artifactId>

        </dependency>

    </dependencies>

 

    <build>

        <plugins>

            <plugin>

                <groupId>org.apache.maven.plugins</groupId>

                <artifactId>maven-surefire-plugin</artifactId>

                <configuration>

                    <skip>true</skip>

                </configuration>

            </plugin>

            <plugin>

                <groupId>org.springframework.boot</groupId>

                <artifactId>spring-boot-maven-plugin</artifactId>

            </plugin>

        </plugins>

        <resources>

            <resource>

                <directory>src/main/resources</directory>

                <includes>

                    <include>**/**</include>

                </includes>

            </resource>

        </resources>

    </build>

 

    <repositories>

        <repository>

            <id>spring-milestones</id>

            <name>Spring Milestones</name>

            <url>https://repo.spring.io/milestone</url>

        </repository>

    </repositories>

    <pluginRepositories>

        <pluginRepository>

            <id>spring-milestones</id>

            <name>Spring Milestones</name>

            <url>https://repo.spring.io/milestone</url>

        </pluginRepository>

    </pluginRepositories>

 

</project>

 

  MySQL数据库数据源类文件

创建名为DataSourceConfig的类,上一篇已经针对该内容详细介绍,在这里就不过多解释了,如果大家有什么不明白可以翻看以前记录【微信公众号“Java精选”,Spring Boot从入门到精通系列文章】,具体代码如下:

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

package com.yoodb.study.demo04.datasource;

 

import org.apache.ibatis.session.SqlSessionFactory;

import org.mybatis.spring.SqlSessionFactoryBean;

import org.mybatis.spring.SqlSessionTemplate;

import org.mybatis.spring.annotation.MapperScan;

import org.springframework.beans.factory.annotation.Qualifier;

import org.springframework.boot.context.properties.ConfigurationProperties;

import org.springframework.boot.jdbc.DataSourceBuilder;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.context.annotation.Primary;

import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

 

import javax.sql.DataSource;

 

@Configuration

@MapperScan(basePackages = "com.yoodb.study.demo04.mapper", sqlSessionFactoryRef = "sqlSessionFactory")

public class DataSourceConfig {

    @Bean(name = "dataSource")

    @Primary

    @ConfigurationProperties(prefix = "spring.datasource")

    public DataSource getDateSourceOne() {

        return DataSourceBuilder.create().build();

    }

 

    @Bean(name = "sqlSessionFactory")

    @Primary

    public SqlSessionFactory oneSqlSessionFactory(@Qualifier("dataSource") DataSource datasource)

            throws Exception {

        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();

        bean.setDataSource(datasource);

        bean.setMapperLocations(

                new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*.xml"));

        return bean.getObject();

    }

     

    @Bean("sqlSessionTemplate")

    @Primary

    public SqlSessionTemplate sqlsessiontemplate(

            @Qualifier("sqlSessionFactory") SqlSessionFactory sessionfactory) {

        return new SqlSessionTemplate(sessionfactory);

    }

}

 

  Redis缓存类文件

创建RedisConfig配置类,具体代码如下:

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

package com.yoodb.study.demo04.datasource;

 

import org.springframework.boot.context.properties.ConfigurationProperties;

import org.springframework.cache.annotation.CachingConfigurerSupport;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.data.redis.connection.RedisConnectionFactory;

import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.data.redis.serializer.StringRedisSerializer;

 

@Configuration

public class RedisConfig extends CachingConfigurerSupport {

 

    @Bean("redisTemplate")

    @ConfigurationProperties(prefix="spring.redis")

    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory){

        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();

        redisTemplate.setConnectionFactory(factory);

 

        //将key的序列化设置成StringRedisSerializer

        StringRedisSerializer keySerializer = new StringRedisSerializer();

        redisTemplate.setKeySerializer(keySerializer);

        redisTemplate.setHashKeySerializer(keySerializer);

 

        redisTemplate.afterPropertiesSet();

        return redisTemplate;

    }

   

}

注:在添加RedisConfig配置时,因为连接redis需要RedisConnection和RedisConnectionFactory,RedisConnection是通过RedisConnectionFactory进行创建。

  实体类文件

新增BootUser实体类文件,具体代码如下:

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

package com.yoodb.study.demo04.bean;

 

import java.io.Serializable;

 

public class BootUser implements Serializable {

    private String id;

    private String name;

    private String detail;

 

    public String getId() {

        return id;

    }

 

    public void setId(String id) {

        this.id = id;

    }

 

    public String getName() {

        return name;

    }

 

    public void setName(String name) {

        this.name = name;

    }

 

    public String getDetail() {

        return detail;

    }

 

    public void setDetail(String detail) {

        this.detail = detail;

    }

}

 

  新增mapper接口类文件

mapper接口类文件,具体代码如下:

1

2

3

4

5

6

package com.yoodb.study.demo04.mapper;

import com.yoodb.study.demo04.bean.BootUser;

import java.util.List;

public interface BootUserMapper {

    List<BootUser> selectAll();

}

 

  新增mapper xml文件

在src/main/resources/mapper/(不存在文件加新建)创建BootUserMapper.xml文件,具体配置信息如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >

<mapper namespace="com.yoodb.study.demo04.mapper.BootUserMapper" >

    <resultMap id="BaseResultMap" type="com.yoodb.study.demo04.bean.BootUser" >

        <id column="id" property="id" jdbcType="VARCHAR" />

        <result column="user_name" property="name" jdbcType="VARCHAR" />

        <result column="detail" property="detail" jdbcType="VARCHAR" />

    </resultMap>

 

    <select id="selectAll" resultMap="BaseResultMap">

    select

         id, user_name, detail

    from boot_user order by detail asc

    </select>

</mapper>

 

  application.properties文件

在application.properties文件中增加MySQL数据库连接配置和Redis缓存连接配置参数,参考信息如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

#MySQL

spring.datasource.jdbc-url=jdbc:mysql://123.57.47.154:3306/dba

spring.datasource.username=root

spring.datasource.password=wangyoodb

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.datasource.max-idle=10

spring.datasource.max-wait=1000

spring.datasource.min-idle=5

spring.datasource.initial-size=5

 

#Redis

#Redis数据库索引(默认为0)

spring.redis.database=0

#Redis服务器地址

spring.redis.host=127.0.0.1

#Redis服务器连接端口

spring.redis.port=6379

注:其中spring.redis.database参数的配置通常使用0即可,Redis在配置的时候可以设置数据库数量,默认为16个,可以理解为数据库的schema。

  创建service类文件

新增文件名BootUserService类文件,具体代码如下:

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

package com.yoodb.study.demo04.service;

 

import java.util.List;

 

import com.yoodb.study.demo04.bean.BootUser;

import com.yoodb.study.demo04.mapper.BootUserMapper;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.stereotype.Service;

 

@Service

public class BootUserService {

 

    @Autowired

    private BootUserMapper bootUserMapper;

 

   @Autowired

    private RedisTemplate redisTemplate;

 

    public List<BootUser> getUsers(){

        List<BootUser> bootUsers = bootUserMapper.selectAll();

        redisTemplate.opsForValue().set("bootUsers",bootUsers);

        List<BootUser> list = (List<BootUser>)redisTemplate.opsForValue().get("bootUsers");

        return list;

    }

 

}

 

  创建controller类文件

新增文件名BootUserController类文件,具体代码如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

package com.yoodb.study.demo04;

 

import java.util.List;

 

import com.yoodb.study.demo04.bean.BootUser;

import com.yoodb.study.demo04.service.BootUserService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

 

@RestController

@RequestMapping("/myt")

public class BootUserController {

    @Autowired

    private BootUserService service;

 

    @RequestMapping("/getUsers")

    public List<BootUser> getUsers() {

        List<BootUser> list = service.getUsers();

        return list;

    }

 

}

mapper的接口、xml文件及实体文件、service层、controller层创建完成后,目录如图:

 

  项目启动

项目启动后访问请求地址:

http://localhost:8080/myt/getUsers

通过浏览器访问输出如下信息:

1

[{"id":"1","name":"admin","detail":"欢迎关注“Java精选”微信公众号,专注程序员推送一些Java开发知识,包括基础知识、各大流行框架(Mybatis、Spring、Spring Boot等)、大数据技术(Storm、Hadoop、MapReduce、Spark等)、数据库(Mysql、Oracle、NoSQL等)、算法与数据结构、面试专题、面试技巧经验、职业规划以及优质开源项目等。其中一部分由小编总结整理,另一部分来源于网络上优质资源,希望对大家的学习和工作有所帮助。"}]

Spring Boot从入门到精通(六)集成Redis实现缓存机制(项目源码springboot-study-demo04)地址:https://github.com/yoodb/springboot。到此讲完了,Spring Boot集成Redis实现缓存机制,实际上就这么简单。不过需要注意使用的时候遇到的坑。~~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章