SpringBoot+Redis做为二级缓存整合的基本Demo

1、Redis简介

一、概述

  Redis 是一个高性能的key-value数据库。 redis的出现,很大程度补偿了memcached这类key/value存储的不足,在部 分场合能够对关系数据库起到很好的补充做用。它提供了Java,C/C++,C#,PHP,JavaScript,Perl,Object-C,Python,Ruby,Erlang等客户端,使用很方便。java

二、优势

(1)数据操做全在内存,读写性能强。
(2)数据结构丰富,支持string,hash,list,set及zset(sorted set)。
(3)支持主从复制,以及数据持久化等mysql

2、Redis的搭建

一、安装

按顺序执行以下命令:web

$ wget http://download.redis.io/releases/redis-5.0.4.tar.gz
$ tar xzf redis-5.0.4.tar.gz
$ cd redis-5.0.4
$ make
$ make install
复制代码

二、测试

开启服务redis

$ redis-server
复制代码

启动客户机交互测试spring

$ redis-cli -p 6379
127.0.0.1:6379> set k1 k2
OK
127.0.0.1:6379> get k1
"k2"
127.0.0.1:6379> 

复制代码

3、基本环境配置

这里使用MyBatis做为持久层框架,使用MySql数据库。sql

一、POM依赖

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <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.0.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>
        </dependency>
    </dependencies>
复制代码

二、YML配置文件

server:
 port: 80
spring:
 http:
 encoding:
 charset: UTF-8
 cache:
 type: redis
 redis:
    #redis服务器地址
 host: 192.168.78.128
    #设置端口号,默认6379
 port: 6379
 datasource:
 driver-class-name: com.mysql.jdbc.Driver
 username: root
 password: 123456
 url: jdbc:mysql://localhost:3306/test
#控制台查看SQL执行情况
logging:
 level:
   com.yurui.rediscache: debug
复制代码

三、测试链接

@RunWith(SpringRunner.class)
@SpringBootTest
public class RediscacheApplicationTests {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    
    @Test
    public void contextLoads() {
        stringRedisTemplate.opsForValue().set("k1","v1");
        System.out.println(stringRedisTemplate.opsForValue().get("k1"));
    }
}
复制代码

测试成功效果: 数据库

测试成功
测试失败的可能缘由:

一、Linux防火墙没设置好
二、启动服务器前配置文件内没有把bind 127.0.0.1注释掉
三、配置文件中没把protected-mode yes改成no缓存

4、三个基本的缓存标签

一、@Cacheable

  @Cacheable能够标记在一个方法上,也能够标记在一个类上。当标记在一个方法上时表示该方法是支持缓存的,当标记在一个类上时则表示该类全部的方法都是支持缓存的。对于一个支持缓存的方法,Spring会在其被调用后将其返回值缓存起来,以保证下次利用一样的参数来执行该方法时能够直接从缓存中获取结果,而不须要再次执行该方法。bash

二、@CachePut

  @CachePut能够声明一个方法支持缓存功能。与@Cacheable不一样的是使用@CachePut标注的方法在执行前不会去检查缓存中是否存在以前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中。服务器

三、@CacheEvict

  @CacheEvict是用来标注在须要清除缓存元素的方法或类上的。当标记在一个类上时表示其中全部的方法的执行都会触发缓存的清除操做。@CacheEvict能够指定的属性有value、key、condition、allEntries和beforeInvocation。

三者共有属性:

  • value(cacheName)
    @Cacheable@CachePut标注时表示生成的缓存的名称,@CacheEvict标注时表示将要清空的缓存的名称。

  • key
    在同一名称(类别)下的缓存,须要惟一的key值来标识惟一的缓存,如未指定则会使用默认策略生成的key;

  • condition
    表示缓存操做发生的条件

@CacheEvict的allEntries和beforeInvocation属性

  • allEntries
      allEntries是boolean类型,表示是否须要清除同一名称的缓存中的全部元素。默认为false,表示不须要。当指定了allEntries为true时,Spring Cache将忽略指定的key,清除全部同一名称的缓存。
  • beforeInvocation
      清除操做默认是在对应方法成功执行以后触发的,即方法若是由于抛出异常而未能成功返回时也不会触发清除操做。使用beforeInvocation能够改变触发清除操做的时间,当咱们指定该属性值为true时,Spring会在调用该方法以前清除缓存中的指定元素。

实例

@Cacheable(cacheNames = "User", key = "#userId")
    @GetMapping("/testCacheable/{userId}")
    public User testCacheable(@PathVariable("userId") Integer userId) {
        // 方法体
    }
复制代码

访问/testCacheable/{userId}时会将返回的User进行缓存,其对应名称为"User",所生成的key为传入进来的userId。

5、基本的Demo

项目结构

项目结构

数据表结构

数据表结构

PO:

@Component
public class User implements Serializable {
    private int userId;
    private String username;
    // setters,getters,toString()方法已被省略
}
复制代码

因为业务逻辑简单,取消了Service层

Mapper:

@Mapper
public interface UserMapper {
    @Insert("insert into user(userId,username) values(#{userId},#{username})")
    int userInsert(User user);

    @Select("select * from user where userId=#{userId}")
    User userQuery(int userId);
}
复制代码

Controller:

@RestController
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @PostMapping("user")
    public String userAdd(User user) {
        return userMapper.userInsert(user) != 0 ? "success" : "fail";
    }

    // 测试Cacheable注解
    @Cacheable(cacheNames = "User", key = "#userId")
    @GetMapping("/testCacheable/{userId}")
    public User testCacheable(@PathVariable("userId") Integer userId) {
        return userMapper.userQuery(userId);
    }

    // 测试CachePut注解
    @CachePut(cacheNames = "User", key = "#userId") //缓存名字为"User","userId"做为key
    @GetMapping("/testCachePut/{userId}")
    public User testCachePut(@PathVariable("userId") Integer userId) {
        return userMapper.userQuery(userId);
    }

    // 测试CacheEvict注解清空指定用户缓存
    @CacheEvict(cacheNames = "User", key = "#userId")
    @GetMapping("/testCacheEvict/{userId}")
    public String testCacheEvict(@PathVariable("userId") Integer userId) {
        return "cache for " + userId + " has been flushed";
    }

    // 测试CacheEvict注解的allEntries属性清空全部用户缓存
    @CacheEvict(cacheNames = "User", allEntries = true)
    @GetMapping("/testAllEntries")
    public String testAllEntries() {
        return "All caches have been flushed";
    }
}
复制代码

主类

@SpringBootApplication
@EnableCaching                          // 开启缓存注解
public class RediscacheApplication {

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

}
复制代码

6、Demo效果测试

准备工做

测试以前,先经过Postman提交数据,向数据库插入两条记录:

插入
清空redis的缓存

127.0.0.1:6379> flushall
OK
复制代码

一、Cacheable

分别访问两次

localhost/testCacheable/1
localhost/testCacheable/2
复制代码

控制台打印状况:

控制台
由上图可得,两条语句均只打印一次,再查询redis:

127.0.0.1:6379> keys *
1) "User::2"
2) "User::1"
127.0.0.1:6379> 
复制代码

可发现,已经使用做为二级缓存。

二、CachePut

清空缓存后分别访问两次

localhost/testCachePut/1
localhost/testCachePut/2
复制代码

再访问

localhost/testCacheable/1
复制代码

控制台打印:

控制台打印
上图共有四条SQL语句执行,可发现每次访问 @CachePut注解标注的方法时都会直接从数据库查询,而且查询结果已经存入缓存。

三、CacheEvict

一、不开启allEntries

测试前先访问两次@Cacheable标注的路径完成缓存,而后分别访问

http://localhost/testCacheEvict/1
http://localhost/testCacheable/1
http://localhost/testCacheable/2
复制代码

控制台打印:

控制台输出
可发现,用户张三的缓存已被清除,李四不受影响,再次访问testCacheable/1会从数据库查询并从新缓存张三。

二、开启allEntries

测试前先访问两边@Cacheable标注的路径完成缓存,而后分别访问

http://localhost/testAllEntries
http://localhost/testCacheable/1
http://localhost/testCacheable/2
复制代码

控制台打印:

控制台输出
可发现,用户张3、李四的缓存均被清空,再次查询会调用数据库从新缓存。

6、CacheManager的定制

一、未定制前

当咱们使用引入redis的starter时,容器中默认使用的是RedisCacheManager。它在操做redis时默认采用JDK的序列化机制,例如redis中查看张三的缓存:

JDK配置
咱们能够经过定制 RedisCacheManager改变采起的序列化机制。

二、进行定制

配置类

@Configuration
public class Config {

    @Bean
    public RedisCacheManager JsonCacheManager(RedisConnectionFactory factory) {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                // 使用GenericJackson2JsonRedisSerializer序列化获得Value
                .serializeValuesWith(RedisSerializationContext.SerializationPair.
                        fromSerializer(new GenericJackson2JsonRedisSerializer()));
        return RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
    }
}


复制代码

缓存以后查看:

Json
到此,已经完成Json的序列化。其余配置可根据 RedisCacheConfiguration中的不一样方法配置。
相关文章
相关标签/搜索