SpringBoot+Mybatis使用Redis做数据缓存(一)查询篇

1.环境准备

1.1创建一个基本的springboot工程引入redis相关的依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

1.2确保本机或虚拟机安装了redis并且启动了redis服务

redis下载地址: 安装并配置redis环境

1.3在springboot中配置Redis

application.yml

spring:
	redis:
    database: 0
    host: 127.0.0.1 # 若使用虚拟机需要换成虚拟机的IP
    port: 6379
    password: root # 换成自己的redis认证密码
    jedis:
      pool:
        max-active: 20
        max-wait: -1
        max-idle: 10
        min-idle: 0
    timeout: 1000

1.4确保redis开启密码认证

修改reids配置文件 Windows版本:redis安装目录下的 redis.windows.conf 或 redis.windows-service.conf (可以查看本机redis服务启动时加载的配置文件)

    查看Windows redis服务启动的配置文件 win + r services.msc 命令进入服务列表页 找到redis服务查看属性 我这里是使用的windows-service.conf这个配置文件 linux版本:/etc/redis.conf 修改配置文件开启密码认证 在配置文件中找到# requirepass foobared 在下面添加 requirepass root root替换成自己的密码(注意这里要保证这句配置文件的前后都要有空行否则可能出现启动服务失败) windows-service.conf配置实例: 保存配置文件后重启redis服务

2.使用在springboot中使用redis

2.1springboot启动类开启缓存

在启动类上加注解 @EnableCaching

2.2写bean、controller、service、dao

这里不再详细介绍直接上代码。 Bean User.java 省略get、set方法 缓存的对象实体类要实现Serializable接口

public class User implements Serializable {
          
   
  /** 用户id */
  private Integer userId;
  /** 用户姓名 */
  private String name;
}

Dao UserDao.java

@Mapper
public interface UserDao {
          
   
	/**
     * 查询所有的用户信息
     *
     * @return 用户信息列表
     */
    @Select("select * from user")
    List<User> findAll();
}

Service UserService.java

public interface UserService {
          
   
    /**
     * 查询所有资源的访问权限设置
     * @return 资源列表
     */
    List<User> findAll();
}

Service实现类 UserServiceImpl.java

@Service
@Slf4j
public class UserServiceImpl implements UserService {
          
   
	@Autowired
    UserDao userDao;
    // 注入RedisTemplate
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public List<User> findAll() {
          
   
    	// 定义key userList
    	String key = "userList";
    	// 设置redis的存储方式
    	ValueOperations<String,List<User>> operations = redisTemplate.opsForValue();
    	List<User> userList;
    	// 查看redis中是否存在缓存数据
    	boolean hasKey = redisTemplate.hasKey(key);
    	if (hasKey) {
          
   
            userList= operations.get(key);
            log.info("==========从缓存中获得数据=========");
            return jurisdictionList;
        } else {
          
   
            log.info("==========从数据库中获得数据=========");
            userList= userDao.findAll();
            // 写入缓存
            operations.set(key, userList);
            return userList;
        }
    }
}

3.启动项目测试

3.1 结果

首次查询会在控制台输出: ==========从数据库中获得数据========= 之后查询会在控制台输出 ==========从缓存中获得数据=========

4.本次仅对查询做介绍

经验分享 程序员 微信小程序 职场和发展