0
点赞
收藏
分享

微信扫一扫

Spring Boot整合Redis

吃面多放酱 2021-09-28 阅读 42
Redis

本篇介绍了Spring Boot整合缓存数据库Redis的两种应用场景



1.应用场景一,直接向Redis读写数据。
2.应用场景二,Redis作为MyBatis的二级缓存,Redis中没有数据时,通过MyBatis读取MySQL中的数据,将读取的结果写入Redis,下次访问时,直接从Redis读数据。

实现步骤

1.添加Maven依赖

在pom.xml中添加如下依赖。

                <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <!-- redis依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>2.2.0.RELEASE</version><!--$NO-MVN-MAN-VER$-->
        </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>
            <version>8.0.18</version><!--$NO-MVN-MAN-VER$-->
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.6</version>
        </dependency>
        <!-- 将redis作为mybatis二级缓存 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
            <version>2.2.0.RELEASE</version><!--$NO-MVN-MAN-VER$-->
        </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-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.62</version>
        </dependency>

2.项目包结构


与Redis有关的主要是utils包下,RedisUtil封装了Redisd的相关API;config包下,RedisConfig配置Redis。稍后,文中会详细介绍。

3.RedisDemoApplication

package com.ljessie.redisdemo;

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


@SpringBootApplication
@MapperScan("com.ljessie.redisdemo.dao")
public class RedisDemoApplication {

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

}

扫描持久层dao包。

4.RedisConfig

package com.ljessie.redisdemo.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.annotation.EnableCaching;
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.*;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@EnableCaching
public class RedisConfig {

    @SuppressWarnings("deprecation")
    @Bean
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 配置连接工厂
        template.setConnectionFactory(factory);

        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer<Object> jacksonSeial = new Jackson2JsonRedisSerializer<Object>(Object.class);

        ObjectMapper om = new ObjectMapper();
        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSeial.setObjectMapper(om);

        // 值采用json序列化
        template.setValueSerializer(jacksonSeial);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());

        // 设置hash key 和value序列化模式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jacksonSeial);
        template.afterPropertiesSet();
        return template;
    }
}

类上面添加@EnableCaching,开启二级缓存,在redisTemplate(RedisConnectionFactory factory)方法中,首先给redisTemplate配置连接工厂,然后给redisTemplate配置序列化方式。
使用StringRedisSerializer来序列化和反序列化redis的key值,使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)。

5.RedisUtil

package com.ljessie.redisdemo.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations.TypedTuple;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    
    /**
               * 有序集合添加之前没有的元素
     */
    public boolean zAdd(String key,Object value,double score) {
        return redisTemplate.opsForZSet().add(key, value,score);
    } 
    
    /**
      * 若集合中已有此元素,则此元素score+传入参数
      * 若没有此元素,则创建元素。
     * @param key
     * @param value
     * @param score
     */
   public void zIncreamentScore(String key,Object value,double score) {
       redisTemplate.opsForZSet().incrementScore(key, value, score);
   }
    
   /**
    * 获取有序集合的大小
    * @param key
    * @return
    */
    public Long zGetSize(String key) {
        return redisTemplate.opsForZSet().size(key);
    }
    
    /**
     * 获取key集合里面,value值的分数
     * @param key
     * @param value
     * @return
     */
    public double zGetScoreByValue(String key,Object value) {
        return redisTemplate.opsForZSet().score(key, value);
    }
    
    /**
     * 对集合按照分数从小到大排序(默认)
     * 指定位置区间0,-1指排序所有元素
     * 得到的值带有score
     * @param key
     * @return 
     */
    public Set<TypedTuple<Object>> zRangeWithScore(String key) {
        return redisTemplate.opsForZSet().rangeWithScores(key, 0, -1);
    }
    
    /**
     * 对集合按照分数从大到小排序
     * @param key
     * @return
     */
    public Set<TypedTuple<Object>> zReverseRangeWithScore(String key){
        return redisTemplate.opsForZSet().reverseRangeWithScores(key, 0, -1);
    }
    
    /**
     * 指定分数区间,从大到小排序
     * @param key
     * @param start
     * @param end
     * @return
     */
    public Set<TypedTuple<Object>> zReverseRangeByScoreWithScores(String key,double start,double end){
        return redisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, start, end);
    }
    
    /**
     * 获取集合中元素的排名(从大到小排序)
     * @param key
     * @param value
     * @return
     */
    public long zGetRank(String key,Object value) {
        return redisTemplate.opsForZSet().reverseRank(key, value);
    }
    

    /**
     * 指定缓存失效时间
     * @param key 键
     * @param time 时间(秒)
     * @return
     */
    public boolean expire(String key,long time){
        try {
            if(time>0){
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据key 获取过期时间
     * @param key 键 不能为null
     * @return 时间(秒) 返回0代表为永久有效
     */
    public long getExpire(String key){
        return redisTemplate.getExpire(key,TimeUnit.SECONDS);
    }

    /**
     * 判断key是否存在
     * @param key 键
     * @return true 存在 false不存在
     */
    public boolean hasKey(String key){
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除缓存
     * @param key 可以传一个值 或多个
     */
    @SuppressWarnings("unchecked")
    public void del(String ... key){
        if(key!=null&&key.length>0){
            if(key.length==1){
                redisTemplate.delete(key[0]);
            }else{
                redisTemplate.delete(CollectionUtils.arrayToList(key));
            }
        }
    }

    //============================String=============================
    /**
     * 普通缓存获取
     * @param key 键
     * @return 值
     */
    public Object get(String key){
        return key==null?null:redisTemplate.opsForValue().get(key);
    }

    /**
     * 普通缓存放入
     * @param key 键
     * @param value 值
     * @return true成功 false失败
     */
    public boolean set(String key,Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 普通缓存放入并设置时间
     * @param key 键
     * @param value 值
     * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
     * @return true成功 false 失败
     */
    public boolean set(String key,Object value,long time){
        try {
            if(time>0){
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            }else{
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 递增
     * @param key 键
     * @param delta 要增加几(大于0)
     * @return
     */
    public long incr(String key, long delta){
        if(delta<0){
            throw new RuntimeException("递增因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, delta);
    }

    /**
     * 递减
     * @param key 键
     * @param delta 要减少几(小于0)
     * @return
     */
    public long decr(String key, long delta){
        if(delta<0){
            throw new RuntimeException("递减因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, -delta);
    }

    //================================Map=================================
    /**
     * HashGet
     * @param key 键 不能为null
     * @param item 项 不能为null
     * @return 值
     */
    public Object hget(String key,String item){
        return redisTemplate.opsForHash().get(key, item);
    }

    /**
     * 获取hashKey对应的所有键值
     * @param key 键
     * @return 对应的多个键值
     */
    public Map<Object,Object> hmget(String key){
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * HashSet
     * @param key 键
     * @param map 对应多个键值
     * @return true 成功 false 失败
     */
    public boolean hmset(String key, Map<String,Object> map){
        try {
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * HashSet 并设置时间
     * @param key 键
     * @param map 对应多个键值
     * @param time 时间(秒)
     * @return true成功 false失败
     */
    public boolean hmset(String key, Map<String,Object> map, long time){
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if(time>0){
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     * @param key 键
     * @param item 项
     * @param value 值
     * @return true 成功 false失败
     */
    public boolean hset(String key,String item,Object value) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     * @param key 键
     * @param item 项
     * @param value 值
     * @param time 时间(秒)  注意:如果已存在的hash表有时间,这里将会替换原有的时间
     * @return true 成功 false失败
     */
    public boolean hset(String key,String item,Object value,long time) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            if(time>0){
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除hash表中的值
     * @param key 键 不能为null
     * @param item 项 可以使多个 不能为null
     */
    public void hdel(String key, Object... item){
        redisTemplate.opsForHash().delete(key,item);
    }

    /**
     * 判断hash表中是否有该项的值
     * @param key 键 不能为null
     * @param item 项 不能为null
     * @return true 存在 false不存在
     */
    public boolean hHasKey(String key, String item){
        return redisTemplate.opsForHash().hasKey(key, item);
    }

    /**
     * hash递增 如果不存在,就会创建一个 并把新增后的值返回
     * @param key 键
     * @param item 项
     * @param by 要增加几(大于0)
     * @return
     */
    public double hincr(String key, String item,double by){
        return redisTemplate.opsForHash().increment(key, item, by);
    }

    /**
     * hash递减
     * @param key 键
     * @param item 项
     * @param by 要减少记(小于0)
     * @return
     */
    public double hdecr(String key, String item,double by){
        return redisTemplate.opsForHash().increment(key, item,-by);
    }

    //============================set=============================
    /**
     * 根据key获取Set中的所有值
     * @param key 键
     * @return
     */
    public Set<Object> sGet(String key){
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据value从一个set中查询,是否存在
     * @param key 键
     * @param value 值
     * @return true 存在 false不存在
     */
    public boolean sHasKey(String key,Object value){
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将数据放入set缓存
     * @param key 键
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sSet(String key, Object...values) {
        try {
            return redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 将set数据放入缓存
     * @param key 键
     * @param time 时间(秒)
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sSetAndTime(String key,long time,Object...values) {
        try {
            Long count = redisTemplate.opsForSet().add(key, values);
            if(time>0) {
                expire(key, time);
            }
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 获取set缓存的长度
     * @param key 键
     * @return
     */
    public long sGetSetSize(String key){
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 移除值为value的
     * @param key 键
     * @param values 值 可以是多个
     * @return 移除的个数
     */
    public long setRemove(String key, Object ...values) {
        try {
            Long count = redisTemplate.opsForSet().remove(key, values);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    //===============================list=================================

    /**
     * 获取list缓存的内容
     * @param key 键
     * @param start 开始
     * @param end 结束  0 到 -1代表所有值
     * @return
     */
    public List<Object> lGet(String key, long start, long end){
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取list缓存的长度
     * @param key 键
     * @return
     */
    public long lGetListSize(String key){
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 通过索引 获取list中的值
     * @param key 键
     * @param index 索引  index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
     * @return
     */
    public Object lGetIndex(String key,long index){
        try {
            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将list放入缓存
     * @param key 键
     * @param value 值
     * @return
     */
    public boolean lSet(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将list放入缓存
     * @param key 键
     * @param value 值
     * @param time 时间(秒)
     * @return
     */
    public boolean lSet(String key, Object value, long time) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将list放入缓存
     * @param key 键
     * @param value 值
     * @return
     */
    public boolean lSet(String key, List<Object> value) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将list放入缓存
     * @param key 键
     * @param value 值
     * @param time 时间(秒)
     * @return
     */
    public boolean lSet(String key, List<Object> value, long time) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据索引修改list中的某条数据
     * @param key 键
     * @param index 索引
     * @param value 值
     * @return
     */
    public boolean lUpdateIndex(String key, long index,Object value) {
        try {
            redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 移除N个值为value
     * @param key 键
     * @param count 移除多少个
     * @param value 值
     * @return 移除的个数
     */
    public long lRemove(String key,long count,Object value) {
        try {
            Long remove = redisTemplate.opsForList().remove(key, count, value);
            return remove;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 模糊查询获取key值
     * @param pattern
     * @return
     */
    public Set<String> keys(String pattern){
        return redisTemplate.keys(pattern);
    }

    /**
     * 使用Redis的消息队列
     * @param channel
     * @param message 消息内容
     */
    public void convertAndSend(String channel, Object message){
        redisTemplate.convertAndSend(channel,message);
    }



    /**
     * 根据起始结束序号遍历Redis中的list
     * @param listKey
     * @param start  起始序号
     * @param end  结束序号
     * @return
     */
    public List<Object> rangeList(String listKey, long start, long end) {
        //绑定操作
        BoundListOperations<String, Object> boundValueOperations = redisTemplate.boundListOps(listKey);
        //查询数据
        return boundValueOperations.range(start, end);
    }
    /**
     * 弹出右边的值 --- 并且移除这个值
     * @param listKey
     */
    public Object rifhtPop(String listKey){
        //绑定操作
        BoundListOperations<String, Object> boundValueOperations = redisTemplate.boundListOps(listKey);
        return boundValueOperations.rightPop();
    }
}

通过key,value普通缓存介绍工具类里面的方法,redisTemplate.opsForValue(),获取ValueOperations<String, Object>对象,然后valueOpeations.set(key,value)和valueOpeations.get(key)向Redis读写数据。

6.RedisController

package com.ljessie.redisdemo.controller;

import com.ljessie.redisdemo.utils.RedisUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/redis")
public class RedisController {

    @Resource
    RedisUtil redisUtil;

    @RequestMapping("/get_string")
    public String testget(String key){
        return (String) redisUtil.get(key);
    }
   
    @RequestMapping("/set_string")
    public String testSet(String key, String value){
        if(redisUtil.set(key,value)){
            return (String) redisUtil.get(key);
        }else{
            return "插入失败";
        }
    }
}

在Controller里面,直接调用redisUtil里面封装的相关方法,即可实现在Redis里面读写数据。

7.application.properties配置

#Redis默认是没有密码的,IP和端口配成自己的就行。
spring.redis.database=0
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
#数据库连接配置
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/nginxdemo?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.type =com.alibaba.druid.pool.DruidDataSource
#打印Sql语句
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#开启MyBatis二级缓存
mybatis.configuration.cache-enabled=true

运行RedisDemoApplication,访问http://localhost:8080/redis/set_string?key=123&value=zbw


再访问http://localhost:8080/redis/get_string?key=123


此时,打开Redis客户端,查看刚才存储的数据,可以看到已经存到Redis里面了。这里要注意,如果直接在Redis里面通过set方式存储键值对,然后用上述路径获取设置的值,会报JsonParseException,这是因为我们在前面的RedisConfig里面配置了序列化方式,通过Redis客户端直接写进去的数据,是没有序列化的,所以当通过应用来读取数据的时候,就会报序列化异常。

下面介绍使用Redis作为MyBatis的二级缓存,配置文件还是上文中使用到的。

8.首先看下数据库里面user表结构


只有两个字段id和name,id是主键,自增;name存储名字。

9.User实体类

package com.ljessie.redisdemo.entity;

import java.io.Serializable;

@SuppressWarnings("serial")
public class User implements Serializable {

    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

实体类的属性和数据库中表的字段一一对应。

10.UserDao

package com.ljessie.redisdemo.dao;

import com.ljessie.redisdemo.entity.User;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;

public interface UserDao {

    @Select("select * from user")
    List<User> findAll();

    @Select("select * from user where id = #{id}")
    User findUserById(int id);

    @Update("UPDATE user SET name=#{name} WHERE id =#{id}")
    int updateUser(int id,String name);
}

11.UserService

package com.ljessie.redisdemo.service;

import com.ljessie.redisdemo.entity.User;

import java.util.List;

public interface UserService {

    int addUser(User user);

    List<User> findAll();

    User findUserById(int id);

    User updateUser(int id,String name);

}

12.UserServiceImpl

package com.ljessie.redisdemo.service.impl;

import com.ljessie.redisdemo.dao.UserDao;
import com.ljessie.redisdemo.entity.User;
import com.ljessie.redisdemo.service.UserService;
import com.ljessie.redisdemo.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;

@Service
@CacheConfig(cacheNames = "userCache") //本类方法开启缓存时,默认使用userCache名称,必须唯一
public class UserServiceImpl implements UserService {

    @Autowired
    UserDao userDao;

    @Resource
    RedisUtil redisUtil;

    @Override
    public int addUser(User user) {
        return 0;
    }

    @Override
    @Cacheable(key = "'allUser'",unless = "#result == null")
    public List<User> findAll() {
        System.out.println("find allUser from DB ");
        return userDao.findAll();
    }

    @Override
    @CachePut(key = "#id")
    public User updateUser(int id, String name) {
        userDao.updateUser(id,name);
        User user = userDao.findUserById(id);
        return user;
    }
    
    /**
     * 如果缓存里面有数据,则从换从里面读
     * 如果缓存没有数据,从数据库里面读
     */
    @Override
    @Cacheable(key = "#id")
    public User findUserById(int id) {
        System.out.println("find user from DB id:"+id);
        return userDao.findUserById(id);
    }
}

@Cacheable注解,表明此方法开启缓存,若缓存里面有数据,则从缓存里面读取数据返回,不会执行方法体;若缓存里面没有数据,则从数据库里面读取数据,并将读取到的数据,写入缓存中。
@CachePut注解,这个注解可以确保方法被执行,同时方法的返回值也被记录到缓存中,实现缓存与数据库的同步更新。

13.MyBatisController

package com.ljessie.redisdemo.controller;

import com.ljessie.redisdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/mybatis")
public class MybatisController {

    @Autowired
    UserService userService;

    @RequestMapping("/find_all")
    public Object findAll(){
        return userService.findAll();
    }

    @RequestMapping("/find_user_by_id")
    public Object findUserById(int id){
        return userService.findUserById(id);
    }

    @RequestMapping("/update_user_by_id")
    public Object updateUser(int id,String name){
        return userService.updateUser(id, name);
    }
}

14.测试

首先,清空Redis数据。


然后,访问http://localhost:8080/mybatis/find_user_by_id?id=12


此时看到控制台打印出SQL语句,证明此条数据是从数据库里面读取的。


再打开Redis客户端,看到刚才查询的id=12的数据已经存储到Redis里面了。


清空控制台,再次访问上述路径,控制台并没有打印出SQL语句,说明并没有进入到@Cacheable注解的方法里面,从Redis里面读取数据返回给前端了。

举报

相关推荐

0 条评论