springboot 整合 redis 使用注解和非注解方式方式缓存数据

1.新建springboot工程(网上很多)

2.pom文件新增依赖 redis 依赖和 mybatis 依赖, mybatis 查询数据使用

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

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

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>

3. springboot启动添加注解   @EnableCaching ,下面代码是我的启动类, 并且整合了mybatis

package com.example.demo;

import de.codecentric.boot.admin.server.config.EnableAdminServer;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@SpringBootApplication
@EnableCaching
@MapperScan("com.example.demo.dao")
@EnableTransactionManagement
public class DemoApplication {

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

}

使用redis 缓存数据步骤

1)配置 application.properties 文件

#redis 地址
spring.redis.host=192.168.1.1
spring.redis.port=6379
spring.redis.password=123456
spring.redis.timeout=4000
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-wait=1000
spring.redis.lettuce.pool.min-idle=1

#缓存类型  指定缓存提供者
spring.cache.type=redis
#缓存名称, 在redis 的key 中前缀会加这个 key的形式是 realTimeCache::
spring.cache.cache-names=realTimeCache

2) 我使用缓存的地方是在service 中所以 :在service 的查询方法中加入以下注解  

@Cacheable(value = "realTimeCache", key = "'student_'+#id" ) 这里面的 value 和 配置文件中的一直, key 是存在redis

中的key (key的形式是 :realTimeCache::student_1  如果你的id是1),代码如下

//注解中id的值和参数中的id值是一致的
//第一次查询id 为1的实体查询数据库 , 第二次查询的时候就会查询缓存
@Cacheable(value = "realTimeCache", key = "'student_'+#id" )
    public Student findByUserId(String id) {
        return studentDao.findByUserId(id);
    }

 3)在redis 中验证一下,使用redis-cli登录redis 客户端

使用 keys * 命令, 会列出所有的key ,会发现里面有一个key是刚才的程序缓存进来的

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值