springboot整合redis,注解方式

本文详细介绍如何使用Spring Boot整合Redis,并利用注解实现缓存管理。包括@Cacheable、@CachePut和@CacheEvict等注解的具体应用及配置示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

之前也实现过springboot整合redis,主要介绍其原理,以及基本的实现,下面是传送门。

(http://blog.youkuaiyun.com/qq_28089993/article/details/73743821)


这次还是spring整合redis,实现方式用到注解。
1、@Cacheable:作用是主要针对方法配置,能够根据方法的请求参数对其结果进行缓存
主要参数说明:
(1)value
缓存的名称,在 spring 配置文件中定义,必须指定至少一个,例如:@Cacheable(value=”mycache”) 或者 @Cacheable(value={”cache1”,”cache2”}。
(2)key :缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合,例如:@Cacheable(value=”testcache”,key=”#userName”)。
(3)condition :缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才进行缓存,例如:@Cacheable(value=”testcache”,condition=”#userName.length()>2。
当然还包括其他的参数,就不一一说明了。


2、@CachePut:作用是主要针对方法配置,能够根据方法的请求参数对其结果进行缓存,和 @Cacheable 不同的是,它每次都会触发真实方法的调用
主要参数说明:

**(1)**value , key 和 condition 参数配置和@Cacheable一样。


3、@CacheEvict:作用是主要针对方法配置,能够根据一定的条件对缓存进行清空
主要参数说明:

(1)value , key 和 condition 参数配置和@Cacheable一样。
(2)allEntries :是否清空所有缓存内容,缺省为 false,如果指定为 true,则方法调用后将立即清空所有缓存,例如:@CachEvict(value=”testcache”,allEntries=true)。
(3)beforeInvocation :是否在方法执行前就清空,缺省为 false,如果指定为 true,则在方法还没有执行的时候就清空缓存,缺省情况下,如果方法执行抛出异常,则不会清空缓存,例如@CachEvict(value=”testcache”,beforeInvocation=true)。

  1. pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.kongl.web</groupId>
  <artifactId>springboot-jpa-redis</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>springboot-jpa-redis</name>
  <url>http://maven.apache.org</url>

  <!-- Spring Boot 启动父依赖 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.1.RELEASE</version>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <mybatis-spring-boot>1.2.0</mybatis-spring-boot>
        <mysql-connector>5.1.39</mysql-connector>
    </properties>

    <dependencies>

        <!-- Spring Boot Web 依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- Spring Boot Redis 依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-redis</artifactId>
            <version>1.3.2.RELEASE</version>
        </dependency>

        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context-support</artifactId>
        </dependency>
        <!-- Spring Boot Test 依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

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


        <!-- MySQL 连接驱动依赖 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql-connector}</version>
        </dependency>

         <!-- 热部署 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
           <scope>true</scope>
        </dependency>
        <!-- Junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <!--fork :  如果没有该项配置,肯呢个devtools不会起作用,即应用不会restart -->
                    <fork>true</fork>
                </configuration>
            </plugin>
        </plugins>
   </build>
</project>
  1. application.properties中redis的一些配置,也可以通过代码实现
## Redis 配置
## Redis数据库索引(默认为0)
spring.redis.database=0
## Redis服务器地址
spring.redis.host=192.168.117.88
## Redis服务器连接端口
spring.redis.port=6379
## Redis服务器连接密码(默认为空)
spring.redis.password=
## 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
## 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
## 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
## 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
## 连接超时时间(毫秒)
spring.redis.timeout=0
  1. RedisConfig.java
@Configuration
@EnableCaching//开启注解 
public class RedisConfig {

    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory){

        RedisTemplate<Object, Object> template=new RedisTemplate<Object, Object>();

        template.setConnectionFactory(connectionFactory);
        //实现序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        //实现序列化和反序列化redis的value值,默认使用JdkSerializationRedisSerializer
        //template.setValueSerializer(new RedisObjectSerializer());
        //template.setValueSerializer();
        return template;

    }


     @Bean
      public CacheManager cacheManager(RedisTemplate<Object, Object> redisTemplate) {
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
        // cacheManager.setCacheNames(Arrays.asList("users", "emptyUsers"));
        cacheManager.setUsePrefix(true);
        // Number of seconds before expiration. Defaults to unlimited (0)
        cacheManager.setDefaultExpiration(1800L);
        return cacheManager;
      }

      //自定义keyGenerator必须实现org.springframework.cache.interceptor.KeyGenerator接口
      @Bean
      public KeyGenerator accountKeyGenerator() {
            return new KeyGenerator(){
                @Override
                public Object generate(Object target, Method method, Object... params) {
                    //first parameter is caching object
                    //second paramter is the name of the method, we like the caching key has nothing to do with method name
                    //third parameter is the list of parameters in the method being called
                    return target.getClass().toString() + "accountId:" + params[0].toString();
                }
            };
        }
}

4、service缓存实现

@Cacheable(value="cat", keyGenerator = "accountKeyGenerator")
    @Override
    public Cat findOneCat(Integer id) {
        System.out.println("开始查询.....");
        try {
            Thread.sleep(3 * 1000l);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("查询结束......");
        Cat cat=catRepository.findOne(id);

        return cat;
    }

5、controller

@RequestMapping(value = "/cat/{id}", method = RequestMethod.GET)
    public Cat findOne(@PathVariable("id") Integer id) {
        long beginTime=System.currentTimeMillis();
        Cat cat=catService.findOneCat(id);
        long time=System.currentTimeMillis()-beginTime;
        System.out.println(time);
        return cat;
    }

结果演示:http://localhost:8080/cat/1 测试缓存
第一次结果:
这里写图片描述
可以看到用时3207
第二、三次结果
这里写图片描述
可以看到3207ms,之后的两次,首先没有执行service的方法打印数据,其次用时大大减少一次用时5ms一次用时2ms,测试完毕。

总结
本着记录和学习的态度去完成本次整合,如果有错误之处请大神之处,谢谢啦。源码如下,本次整合了Springboot+redis+SpringJPA,所以源码直接运行即可,记得数据库写两条数据。
springboot-redis-jpa代码

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值