温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在spring中使用redis缓存数据

发布时间:2021-05-14 17:54:09 来源:亿速云 阅读:182 作者:Leah 栏目:编程语言

怎么在spring中使用redis缓存数据?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

为什么要用redis做缓存:

(1)异常快速:Redis的速度非常快,每秒能执行约11万集合,每秒约81000+条记录。
(2)支持丰富的数据类型:Redis支持最大多数开发人员已经知道像列表,集合,有序集合,散列数据类型。这使得它非常容易解决各种各样的问题,因为我们知道哪些问题是可以处理通过它的数据类型更好。
(3)操作都是原子性:所有Redis操作是原子的,这保证了如果两个客户端同时访问的Redis服务器将获得更新后的值。
(4)多功能实用工具:Redis是一个多实用的工具,可以在多个用例如缓存,消息,队列使用(Redis原生支持发布/订阅),任何短暂的数据,应用程序,如Web应用程序会话,网页命中计数等。

缓存实现思路:

  • 项目中配置好redis账户等属性文件(redis.properties)

  • 整合到spring容器中(application-redis.xml)

  • 编写redis工具类

一、项目中配置好redis账户等属性文件(redis.properties)

#ip地址
redis.hostName=yourIpAddress
#端口号
redis.port=6379
#如果有密码
redis.password=yourRedisPassword
#客户端超时时间单位是毫秒 默认是2000
redis.timeout=10000 
#最大空闲数
redis.maxIdle=300
#连接池的最大数据库连接数。设为0表示无限制,如果是jedis 2.4以后用redis.maxTotal
#redis.maxActive=600
#控制一个pool可分配多少个jedis实例,用来替换上面的redis.maxActive,如果是jedis 2.4以后用该属性
redis.maxTotal=1000
#最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。
redis.maxWaitMillis=1000
#连接的最小空闲时间 默认1800000毫秒(30分钟)
redis.minEvictableIdleTimeMillis=300000
#每次释放连接的最大数目,默认3
redis.numTestsPerEvictionRun=1024
#逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1
redis.timeBetweenEvictionRunsMillis=30000
#是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个
redis.testOnBorrow=true
#在空闲时检查有效性, 默认false
redis.testWhileIdle=true

二、整合到spring容器中(application-redis.xml)

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans"  
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
  xmlns:context="http://www.springframework.org/schema/context"  
  xmlns:mvc="http://www.springframework.org/schema/mvc"  
  xmlns:cache="http://www.springframework.org/schema/cache" 
  xmlns:aop="http://www.springframework.org/schema/aop" 
  xsi:schemaLocation="http://www.springframework.org/schema/beans   
            http://www.springframework.org/schema/beans/spring-beans.xsd   
            http://www.springframework.org/schema/context   
            http://www.springframework.org/schema/context/spring-context.xsd   
            http://www.springframework.org/schema/mvc   
            http://www.springframework.org/schema/mvc/spring-mvc.xsd 
            http://www.springframework.org/schema/cache  
            http://www.springframework.org/schema/cache/spring-cache.xsd
            http://www.springframework.org/schema/aop  
            http://www.springframework.org/schema/aop/spring-aop.xsd">
  <!-- 加载配置文件 -->
  <context:property-placeholder ignore-unresolvable="true" location="classpath:properties/redis.properties" />
  <!-- redis连接池配置--> 
  <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig" > 
    <!--最大空闲数--> 
    <property name="maxIdle" value="${redis.maxIdle}" /> 
    <!--连接池的最大数据库连接数 -->
    <property name="maxTotal" value="${redis.maxTotal}" />
    <!--最大建立连接等待时间--> 
    <property name="maxWaitMillis" value="${redis.maxWaitMillis}" /> 
    <!--逐出连接的最小空闲时间 默认1800000毫秒(30分钟)-->
    <property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}" /> 
    <!--每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3-->
    <property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}" /> 
    <!--逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1-->
    <property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}" /> 
    <!--是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个--> 
    <property name="testOnBorrow" value="${redis.testOnBorrow}" /> 
    <!--在空闲时检查有效性, 默认false -->
    <property name="testWhileIdle" value="${redis.testWhileIdle}" /> 
  </bean >
  <!--redis连接工厂 -->
  <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" destroy-method="destroy"> 
    <property name="poolConfig" ref="jedisPoolConfig"></property> 
    <!--IP地址 -->
    <property name="hostName" value="${redis.hostName}"></property> 
    <!--端口号 -->
    <property name="port" value="${redis.port}"></property> 
    <!--如果Redis设置有密码 -->
    <property name="password" value="${redis.password}" />
    <!--客户端超时时间单位是毫秒 -->
    <property name="timeout" value="${redis.timeout}"></property> 
  </bean> 
  <!--redis操作模版,使用该对象可以操作redis -->
  <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" > 
    <property name="connectionFactory" ref="jedisConnectionFactory" /> 
    <!--如果不配置Serializer,那么存储的时候缺省使用String,如果用User类型存储,那么会提示错误User can't cast to String!! --> 
    <property name="keySerializer" > 
      <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> 
    </property> 
    <property name="valueSerializer" > 
      <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" /> 
    </property> 
    <property name="hashKeySerializer"> 
      <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/> 
    </property> 
    <property name="hashValueSerializer"> 
      <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/> 
    </property> 
    <!--开启事务 -->
    <property name="enableTransactionSupport" value="true"></property>
  </bean > 
  <!--自定义redis工具类,在需要缓存的地方注入此类 -->
  <bean id="redisUtil" class="com.neuedu.crm.utils.RedisUtil">
    <property name="redisTemplate" ref="redisTemplate" />
  </bean> 
</beans>

三、编写redis工具类

package com.neuedu.crm.utils;
import java.io.Serializable;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
/**
 * Redis工具类
 * :用于缓存数据
 *
 */
public class RedisUtil {
  private Logger logger = LoggerFactory.getLogger(RedisUtil.class);
  private RedisTemplate<Serializable, Object> redisTemplate;
  public void setRedisTemplate(RedisTemplate<Serializable, Object> redisTemplate) {
    this.redisTemplate = redisTemplate;
  }
  /**
   * 批量删除对应的value
   *
   * @param keys
   */
  public void remove(final String... keys) {
    for (String key : keys) {
      remove(key);
    }
  }
  /**
   * 批量删除key
   *
   * @param pattern
   */
  public void removePattern(final String pattern) {
    Set<Serializable> keys = redisTemplate.keys(pattern);
    if (keys.size() > 0) {
      redisTemplate.delete(keys);
    }
  }
  /**
   * 删除对应的value
   *
   * @param key
   */
  public void remove(final String key) {
    logger.info("要移除的key为:" + key);
    if (exists(key)) {
      redisTemplate.delete(key);
    }
  }
  /**
   * 判断缓存中是否有对应的value
   *
   * @param key
   * @return
   */
  public boolean exists(final String key) {
    logger.info("要验证是否存在的key为:" + key);
    return redisTemplate.hasKey(key);
  }
  /**
   * 读取缓存
   *
   * @param key
   * @return
   */
  public Object get(final String key) {
    Object result = null;
    ValueOperations<Serializable, Object> operations = redisTemplate
        .opsForValue();
    result = operations.get(key);
    return result;
  }
  /**
   * 写入缓存
   *
   * @param key
   * @param value
   * @return
   */
  public boolean set(final String key, Object value) {
    boolean result = false;
    try {
      ValueOperations<Serializable, Object> operations = redisTemplate
          .opsForValue();
      operations.set(key, value);
      result = true;
    } catch (Exception e) {
      logger.error("系统异常",e);
    }
    return result;
  }
  /**
   * 写入缓存
   *
   * @param key
   * @param value
   * @return
   */
  public boolean set(final String key, Object value, Long expireTime) {
    boolean result = false;
    try {
      ValueOperations<Serializable, Object> operations = redisTemplate
          .opsForValue();
      operations.set(key, value);
      redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
      result = true;
    } catch (Exception e) {
      logger.error("系统异常",e);
    }
    return result;
  }
}

关于怎么在spring中使用redis缓存数据问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI