SpringBoot入门,整合Redis实现缓存

1.引言

本文继续沿用上几篇博客的基础,在此之上整合Redis,实现缓存功能,具体环境搭建,请参考我之前的博客,在这里不做赘述。

(1)SpringBoot入门,快速搭建简单Web应用环境

(2)SpringBoot入门,整合Mybatis并使用Mybatis-Generator自动生成所需代码

(3)SpringBoot入门,整合Pagehelper分页插件

2.Window下安装Redis

下载Redis,地址https://github.com/MicrosoftArchive/redis/releases,我这里下载的是.msi格式的3.2.100版本。如图所示:

下载完后双击安装,自定义安装路径,一路next就行。安装完后,右击此电脑→管理→服务和应用程序→服务,可以看到Redis的服务正在运行。

然后我们从命令号进入到Redis的安装目录,输入redis-cli查看redis是否安装成功。

至此Redis安装完成。我们可以进行一些简单的小测试

127.0.0.1:6379> set name "hello" //设置key=name,value="hello",成功返回OK
OK
127.0.0.1:6379> get name//获取key=name的value值
"hello"
127.0.0.1:6379> del name//删除key=name
(integer) 1

3.安装RedisDesktopManager(可选)

如果你嫌使用命令行操作不方便,那么可以安装Redis的可视化工具RedisDesktopManager。下载地址:https://github.com/uglide/RedisDesktopManager/releases,我这里安装的也是最新的0.9.3。

下载完后双击安装就行,安装完后启动它连接我们的redis

由于我们没有设置登录密码,所以验证那栏我们不用填,之后点击“好“连接redis,之后我们就可以在图形界面中操作redis了,这里就不多说了,自行操作就行。

4.SpringBoot整合Redis

(1)在pom文件中引入所需的依赖

<!-- redis -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
    <version>2.4.2</version>
</dependency>

(2)在配置文件application.properties中对redis进行配置,我们没有设置密码,所以为空

#整合redis
spring.redis.database=0
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-wait=-1ms
spring.redis.jedis.pool.max-idle=8
spring.redis.lettuce.pool.min-idle=0
spring.redis.timeout=10000ms

至此,redis整合已经完成,下面开始测试。

5.测试一

(1)在入口程序中添加@EnableCaching注解,开启缓存,具体代码如下:

package com.example;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@MapperScan("com.example.dao")
@EnableCaching
public class FirstApplication {

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

(2)配置文件中开启druid二级缓存,这里使用的是druid链接池

#数据源1
#spring.datasource.url=jdbc:mysql://127.0.0.1:3306/first?useUnicode=true&characterEncoding=utf-8
#spring.datasource.username=root
#spring.datasource.password=123456
#spring.datasource.driver-class-name=com.mysql.jdbc.Driver

#druid数据源
spring.datasource.name=mysql_test
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/first?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456
#数据源配置,初始化大小、最小、最大
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
#连接等待超时时间
spring.datasource.maxWait=60000
#配置隔多久进行一次检测(检测可以关闭的空闲连接)
spring.datasource.timeBetweenEvictionRunsMillis=60000
#配置连接在池中的最小生存时间
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
# 打开PSCache,并且指定每个连接上PSCache的大小
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
spring.datasource.filters=stat,wall,log4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
#开启二级缓存
spring.datasource.cachePrepStmts=true

(3)在controller包下新建一个RedisController类进行测试,代码如下

package com.example.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RedisController {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @GetMapping("/redis")
    public String redis(){
        //设置key="first",value="Hello World"
        stringRedisTemplate.opsForValue().set("first","Hello World");
        //取出key="first"的value值
        return stringRedisTemplate.opsForValue().get("first");
    }
}

(4)启动程序,在浏览器中输入localhost:8080/redis,查看效果。

可以看到我们从redis中成功获取到了我们设置的值,同样我们可以使用可视化程序查看我们设置的key-value.配置文件中我们配置的database=0,所以我们在db0中查看。

ok,没有问题。

6.测试二

在测试一中,我们只是简单的向redis中添加了key-value,下面我们来实现真正的数据库缓存。

(1)首先将我们的Person实体类实现序列化接口(必须

(2)在PersonService中新加一个查找Person的方法

package com.example.service;

import com.example.bean.Person;

import java.util.List;

public interface PersonService {
    List<Person> getAllPerson();

    Integer addPerson(Person person);
    //根据id查找Person
    Person getPerson(Integer id);

}

(3)在PersonServiceImpl中对方法进行实现,并配置缓存的内容

@Service
@CacheConfig(cacheNames = "personCache")
public class PersonServiceImpl implements PersonService {

    @Autowired
    private PersonMapper personMapper;

    @Override
    public List<Person> getAllPerson() {
        return personMapper.selectByExample(null);
    }

    @Override
    @Cacheable
    public Person getPerson(Integer id) {
        return personMapper.selectByPrimaryKey(id);
    }
}

这里用到了两个注解@CacheConfig和@Cacheable

@CacheConfig主要用于配置该类中会用到的一些共用的缓存配置。@CacheConfig(cacheNames = "personCache")
配置了该数据访问对象中返回的内容将存储于名为personCache的缓存对象中,我们也可以不使用该注解,直接通过@Cacheable自己配置缓存集的名字来定义。
@Cacheable先查缓存,没有在执行下面的方法,然后在将结果缓存。如果不指定key,则默认key为id的值。即上面的@Cacheable等同于@Cacheable(key="#id")

更多注解及用法请参考官方文档

(4)在PersonController中新加getPersonById的方法

@GetMapping("/getPersonById/{personId}")
public String getPersonById(Model model,@PathVariable Integer personId){
    Person person = personService.getPerson(personId);
    model.addAttribute("person",person);
    return "selectPage";
}

(5)在templates文件夹下新建selectPage.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div align="center">
    <table border="1">
        <tr>
            <th>id</th>
            <th>name</th>
            <th>sex</th>
            <th>age</th>
        </tr>
        <tr>
            <td th:text="${person.id}"></td>
            <td th:text="${person.name}"></td>
            <td th:text="${person.sex}"></td>
            <td th:text="${person.age}"></td>
        </tr>
    </table>
</div>
</body>
</html>

(6)启动程序,在浏览器中输入http://localhost:8080/getPersonById/1查看结果,并在Redis可视化工具中查看是否缓存成功

由于序列化了,所以我们看不到值的内容。

ok,测试成功,当我们再次查找id为1的person的时候,我们会首先查找缓存内容,再去查找数据库。

7.扩展,设置Redis登陆密码

进入到Redis的安装目录,打开redis.windows-service.conf配置文件(我用Editplus)。找到requirepass 添加自己想要设置的密码

之后重启Redis服务使之生效。在连接Redis时,就需要添加密码了。

 

SpringBoot整合redis就介绍到这里,欢迎大家评论和转发,如有问题请提出,我会及时改正!

 

 

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值