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實現緩存機制,實際上就這麼簡單。不過需要注意使用的時候遇到的坑。~~

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