zoukankan      html  css  js  c++  java
  • springboot使用redis

    概述

    springboot通常整合redis,采用的是RedisTemplate的形式,除了这种形式以外,还有另外一种形式去整合,即采用spring支持的注解进行访问缓存.

    准备工作

    pom.xml

     1        <dependency>
     2             <groupId>redis.clients</groupId>
     3             <artifactId>jedis</artifactId>
     4             <version>2.7.3</version>
     5         </dependency>
     6         <dependency>
     7             <groupId>org.springframework.data</groupId>
     8             <artifactId>spring-data-redis</artifactId>
     9             <version>1.7.2.RELEASE</version>
    10         </dependency>
    11         <dependency>
    12             <groupId>org.springframework.boot</groupId>
    13             <artifactId>spring-boot-starter-redis</artifactId>
    14             <version>RELEASE</version>
    15         </dependency>
    16                 

    application.properties

     1 # REDIS (RedisProperties)
     2 # Redis数据库索引(默认为0)
     3 spring.redis.database=0
     4 # Redis服务器地址
     5 spring.redis.host=127.0.0.1
     6 # Redis服务器连接端口
     7 spring.redis.port=6379
     8 # 连接池最大连接数(使用负值表示没有限制)
     9 spring.redis.pool.max-active=8
    10 # 连接池最大阻塞等待时间(使用负值表示没有限制)
    11 spring.redis.pool.max-wait=-1
    12 # 连接池中的最大空闲连接
    13 spring.redis.pool.max-idle=8
    14 # 连接池中的最小空闲连接
    15 spring.redis.pool.min-idle=0
    16 # 连接超时时间(毫秒)
    17 spring.redis.timeout=0

    Redis配置类

     1 package cn.chenlove.config;
     2 
     3 import org.apache.log4j.Logger;
     4 import org.springframework.beans.factory.annotation.Value;
     5 import org.springframework.cache.annotation.CachingConfigurerSupport;
     6 import org.springframework.cache.annotation.EnableCaching;
     7 import org.springframework.context.annotation.Bean;
     8 import org.springframework.context.annotation.Configuration;
     9 
    10 import redis.clients.jedis.JedisPool;
    11 import redis.clients.jedis.JedisPoolConfig;
    12 
    13 @Configuration
    14 @EnableCaching
    15 public class RedisConfig  extends CachingConfigurerSupport{
    16     @Value("${spring.redis.host}")
    17     private String host;
    18 
    19     @Value("${spring.redis.port}")
    20     private int port;
    21 
    22     @Value("${spring.redis.timeout}")
    23     private int timeout;
    24 
    25     @Value("${spring.redis.pool.max-idle}")
    26     private int maxIdle;
    27 
    28     @Value("${spring.redis.pool.max-wait}")
    29     private long maxWaitMillis;
    30 
    31     @Bean
    32     public JedisPool redisPoolFactory() {
    33         Logger.getLogger(getClass()).info("JedisPool注入成功!!");
    34         Logger.getLogger(getClass()).info("redis地址:" + host + ":" + port);
    35         JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
    36         jedisPoolConfig.setMaxIdle(maxIdle);
    37         jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
    38 
    39         JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout);
    40 
    41         return jedisPool;
    42     }
    43 }

    可以看出,我们这里主要配置了两个东西,cacheManager方法配置了一个缓存名称,它的名字叫做thisredis,当我们要在方法注解里面使用到它的时候,就要根据名称进行区分不同缓存.同时设置了缓
    存的过期时间.redisTemplate则是比较常见的,我们设置了RedisTemplate,因此在代码里面,我们也可以通过@Autowired注入RedisTemplate来操作redis.

    使用

    接下来就是如何使用注解啦,这一步反而是最简单的.其实只用到了两个注解,@Cacheable和@CacheEvict.第一个注解代表从缓存中查询指定的key,如果有,从缓存中取,不再执行方法.如果没有则执
    行方法,并且将方法的返回值和指定的key关联起来,放入到缓存中.而@CacheEvict则是从缓存中清除指定的key对应的数据.使用的代码如下:

     1     //有参数
     2     @Cacheable(value="thisredis", key="'users_'+#id")
     3     public User findUser(Integer id) {
     4         User user = new User();
     5         user.setUsername("hlhdidi");
     6         user.setPassword("123");
     7         user.setUid(id.longValue());
     8         System.out.println("log4j2坏啦?");
     9         logger.info("输入user,用户名:{},密码:{}",user.getUsername(),user.getPassword());
    10         return user;
    11      }
    12 
    13       @CacheEvict(value="thisredis",   key="'users_'+#id",condition="#id!=1")
    14       public void delUser(Integer id) {
    15         // 删除user
    16            System.out.println("user删除");
    17        }
    18 
    19        //无参数
    20        @RequestMapping("/get")
    21     @Cacheable(value="thisredis")
    22     @ResponseBody
    23     public List<User> xx(){
    24         return userMapper.selectAll();
    25     }
    26     @RequestMapping("/get3")
    27     @CacheEvict(value="thisredis")
    28     @ResponseBody
    29     public String xx3(){
    30         return "ok";
    31     }

    可以看出,我们用@Cacheable的value属性指定具体缓存,并通过key将其放入缓存中.这里key非常灵活,支持spring的el表达式,可以通过方法参数产生可变的key(见findUser方法),也可以通过其指定在
    什么情况下,使用/不使用缓存(见delUser方法).

  • 相关阅读:
    怎么知道windows dll是32位还是64位?
    Controlling IntelliSense Through Macros VS2005 sp1 vs2008
    Largeint.lib
    获取设备管理器中显卡
    匿名管道 双向通信 需要两个
    数据库连接方式详细介绍(转载)
    算法复习1(冒泡、快排、折半)
    EXTJS学习方案<一>
    算法复习2(全排序,从M取N个数) *不考虑重复数据
    confluence的安装流程
  • 原文地址:https://www.cnblogs.com/chenlove/p/9750297.html
Copyright © 2011-2022 走看看