欢迎投稿

今日深度:

spring整合redis实现数据缓存的实例代码,

spring整合redis实现数据缓存的实例代码,


数据缓存原因:有些数据比较多,如果每次访问都要进行查询,无疑给数据库带来太大的负担,将一些庞大的查询数据并且更新次数较少的数据存入redis,能为系统的性能带来良好的提升。

业务逻辑思路:登入系统,访问数据时,检查redis是否有缓存,有则直接从redis中提取,没有则从数据库查询出,并存入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;
  }
}

注意点:redis工具类由spring进行托管,则在需要缓存的地方注入redis工具类即可。

总结

以上所述是小编给大家介绍的spring整合redis实现数据缓存的实例代码,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!

www.htsjk.Com true http://www.htsjk.com/redis/29076.html NewsArticle spring整合redis实现数据缓存的实例代码, 数据缓存原因:有些数据比较多,如果每次访问都要进行查询,无疑给数据库带来太大的负担,将一些庞大的查询数据并且更新次数较少的数据...
评论暂时关闭