Spring整合Redis缓存

 通常而言目前的数据库分类有几种,包括 SQL/NSQL,,关系数据库,键值数据库等等 等,分类的标准也不以,Redis本质上也是一种键值数据库的,但它在保持键值数据库简单快捷特点的同时,又吸收了部分关系数据库的优点。从而使它的位置处于关系数据库和键值数 据库之间。Redis不仅能保存Strings类型的数据,还能保存Lists类型(有序)和Sets类型(无序)的数据,而且还能完成排序(SORT) 等高级功能,在实现INCR,SETNX等功能的时候,保证了其操作的原子性,除此以外,还支持主从复制等功能。

现在很流行用redis做缓存,本项目也先简单地将redis缓存整合到SSM项目之中,主要有以下几步:

1.pom.xml中引入jar包

	<!--redis-->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.6.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.8.0</version>
        </dependency>

2.新建spring-redis.xml配置文件

要启用缓存支持,我们需要在spring的配置文件中进行配置 。Redis 不是应用的共享内存,它只是一个内存服务器,就像 MySql 似的,我们需要将应用连接到它并使用某种“语言”进行交互,因此我们还需要一个连接工厂以及一个 Spring 和 Redis 对话要用的 RedisTemplate,这些都是 Redis 缓存所必需的配置:
<?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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans      
                        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd      
                        http://www.springframework.org/schema/context      
                        http://www.springframework.org/schema/context/spring-context-4.2.xsd      
                        http://www.springframework.org/schema/mvc      
                        http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd  
                        http://www.springframework.org/schema/cache   
                        http://www.springframework.org/schema/cache/spring-cache-4.2.xsd">

	<!-- 缓存的层级-->
 	<context:component-scan base-package="com.lw.common.utils" />
	
	<context:property-placeholder location="classpath:redis.properties" />

	<!-- redis 相关配置 -->
	<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
		<property name="maxIdle" value="${redis.maxIdle}" />
		<property name="maxWaitMillis" value="${redis.maxWait}" />
		<property name="testOnBorrow" value="${redis.testOnBorrow}" />
	</bean>

	<!-- redis单节点数据库连接配置 -->
	<bean id="JedisConnectionFactory"
		class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
		<property name="hostName" value="${redis.host}" />
		<property name="port" value="${redis.port}" />
		<property name="password" value="${redis.pass}" />
		<property name="poolConfig" ref="poolConfig" />
	</bean>

	<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
		<property name="connectionFactory" ref="JedisConnectionFactory" />
	</bean>
</beans>    
redis.properties中设置了redis服务器的所需的参数:

 
  
redis.host=127.0.0.1
redis.port=6379
redis.pass=password
#控制一个pool最多有多少个状态为idle(空闲)的jedis实例
redis.maxIdle=100
redis.maxActive=300
# 表示当borrow(引入)一个jedis实例时,最大的等待时间,如果超过等待时间(毫秒),则直接抛出JedisConnectionException;    
redis.maxWait=3000  
# 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的    
redis.testOnBorrow=true  
配置完成后将配置文件引入到Spring配置文件中
<!-- 引入同文件夹下的redis属性配置文件 -->
<import resource="spring-redis.xml" />

3.定义redisCache类来实现对redis的操作
package com.lw.common.cache;

import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;


@Component
public class RedisCache {

  public final static String CAHCENAME = "cache";// 缓存名
  public final static int CAHCETIME = 60;// 默认缓存时间

  @Resource
  private RedisTemplate
    
    
     
      redisTemplate;
//  private SimpleCacheManager cacheManager;

  public 
     
     
      
       boolean putCache(String key, T obj) {
   final byte[] bkey = key.getBytes();
   final byte[] bvalue = ProtoStuffSerializerUtil.serialize(obj);
   boolean result = redisTemplate.execute(new RedisCallback
      
      
       
       () {
    @Override
    public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
     return connection.setNX(bkey, bvalue);
    }
   });
   return result;
  }

  public 
       
       
        
         void putCacheWithExpireTime(String key, T obj, final long expireTime) {
   final byte[] bkey = key.getBytes();
   final byte[] bvalue = ProtoStuffSerializerUtil.serialize(obj);
   redisTemplate.execute(new RedisCallback
        
        
          () { @Override public Boolean doInRedis(RedisConnection connection) throws DataAccessException { connection.setEx(bkey, expireTime, bvalue); return true; } }); } public 
         
           boolean putListCache(String key, List 
          
            objList) { final byte[] bkey = key.getBytes(); final byte[] bvalue = ProtoStuffSerializerUtil.serializeList(objList); boolean result = redisTemplate.execute(new RedisCallback 
           
             () { @Override public Boolean doInRedis(RedisConnection connection) throws DataAccessException { return connection.setNX(bkey, bvalue); } }); return result; } public 
            
              boolean putListCacheWithExpireTime(String key, List 
             
               objList, final long expireTime) { final byte[] bkey = key.getBytes(); final byte[] bvalue = ProtoStuffSerializerUtil.serializeList(objList); boolean result = redisTemplate.execute(new RedisCallback 
              
                () { @Override public Boolean doInRedis(RedisConnection connection) throws DataAccessException { connection.setEx(bkey, expireTime, bvalue); return true; } }); return result; } public 
               
                 T getCache(final String key, Class 
                
                  targetClass) { byte[] result = redisTemplate.execute(new RedisCallback 
                 
                   () { @Override public byte[] doInRedis(RedisConnection connection) throws DataAccessException { return connection.get(key.getBytes()); } }); if (result == null) { return null; } return ProtoStuffSerializerUtil.deserialize(result, targetClass); } public 
                  
                    List 
                   
                     getListCache(final String key, Class 
                    
                      targetClass) { byte[] result = redisTemplate.execute(new RedisCallback 
                     
                       () { @Override public byte[] doInRedis(RedisConnection connection) throws DataAccessException { return connection.get(key.getBytes()); } }); if (result == null) { return null; } return ProtoStuffSerializerUtil.deserializeList(result, targetClass); } /** * 精确删除key * * @param key */ public void deleteCache(String key) { redisTemplate.delete(key); } /** * 模糊删除key * * @param pattern */ public void deleteCacheWithPattern(String pattern) { Set 
                      
                        keys = redisTemplate.keys(pattern); redisTemplate.delete(keys); } /** * 清空所有缓存 */ public void clearCache() { deleteCacheWithPattern(RedisCache.CAHCENAME+"|*"); } } 
                       
                      
                     
                    
                   
                  
                 
                
               
              
             
            
           
          
        
       
       
      
      
     
     
    
    
其中ProtoStuffSerializerUtil为一个序列化和反序列化 对象的工具类
package com.lw.common.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema;

/**
 * 序列话工具
 */
public class ProtoStuffSerializerUtil {

	/**
	 * 序列化对象
	 * @param obj
	 * @return
	 */
	public static 
     
     
      
       byte[] serialize(T obj) {
		if (obj == null) {
			throw new RuntimeException("序列化对象(" + obj + ")!");
		}
		@SuppressWarnings("unchecked")
		Schema
      
      
       
        schema = (Schema
       
       
        
        ) RuntimeSchema.getSchema(obj.getClass());
		LinkedBuffer buffer = LinkedBuffer.allocate(1024 * 1024);
		byte[] protostuff = null;
		try {
			protostuff = ProtostuffIOUtil.toByteArray(obj, schema, buffer);
		} catch (Exception e) {
			throw new RuntimeException("序列化(" + obj.getClass() + ")对象(" + obj + ")发生异常!", e);
		} finally {
			buffer.clear();
		}
		return protostuff;
	}

	/**
	 * 反序列化对象
	 * @param paramArrayOfByte
	 * @param targetClass
	 * @return
	 */
	public static 
        
        
         
          T deserialize(byte[] paramArrayOfByte, Class
         
         
           targetClass) { if (paramArrayOfByte == null || paramArrayOfByte.length == 0) { throw new RuntimeException("反序列化对象发生异常,byte序列为空!"); } T instance = null; try { instance = targetClass.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException("反序列化过程中依据类型创建对象失败!", e); } Schema 
          
            schema = RuntimeSchema.getSchema(targetClass); ProtostuffIOUtil.mergeFrom(paramArrayOfByte, instance, schema); return instance; } /** * 序列化列表 * @param objList * @return */ public static 
           
             byte[] serializeList(List 
            
              objList) { if (objList == null || objList.isEmpty()) { throw new RuntimeException("序列化对象列表(" + objList + ")参数异常!"); } @SuppressWarnings("unchecked") Schema 
             
               schema = (Schema 
              
                ) RuntimeSchema.getSchema(objList.get(0).getClass()); LinkedBuffer buffer = LinkedBuffer.allocate(1024 * 1024); byte[] protostuff = null; ByteArrayOutputStream bos = null; try { bos = new ByteArrayOutputStream(); ProtostuffIOUtil.writeListTo(bos, objList, schema, buffer); protostuff = bos.toByteArray(); } catch (Exception e) { throw new RuntimeException("序列化对象列表(" + objList + ")发生异常!", e); } finally { buffer.clear(); try { if (bos != null) { bos.close(); } } catch (IOException e) { e.printStackTrace(); } } return protostuff; } /** * 反序列化列表 * @param paramArrayOfByte * @param targetClass * @return */ public static 
               
                 List 
                
                  deserializeList(byte[] paramArrayOfByte, Class 
                 
                   targetClass) { if (paramArrayOfByte == null || paramArrayOfByte.length == 0) { throw new RuntimeException("反序列化对象发生异常,byte序列为空!"); } Schema 
                  
                    schema = RuntimeSchema.getSchema(targetClass); List 
                   
                     result = null; try { result = ProtostuffIOUtil.parseListFrom(new ByteArrayInputStream(paramArrayOfByte), schema); } catch (IOException e) { throw new RuntimeException("反序列化对象列表发生异常!", e); } return result; } } 
                    
                   
                  
                 
                
               
              
             
            
           
         
        
        
       
       
      
      
     
     
工具类又需要引入额外的jar包
<dependency>
	<groupId>com.dyuproject.protostuff</groupId>
	<artifactId>protostuff-core</artifactId>
	<version>1.0.8</version>
</dependency>

<dependency>
	<groupId>com.dyuproject.protostuff</groupId>
	<artifactId>protostuff-runtime</artifactId>
	<version>1.0.8</version>
</dependency>
至此Spring整合redis缓存的配置工作便准备完成,下面便可在service层使用
package com.lw.service;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.lw.common.utils.RedisCache;
import com.lw.dao.UserMapper;
import com.lw.entity.User;

@Service
public class UserService {
  
  private static final Logger log = LoggerFactory.getLogger(UserService.class);
  
  @Resource
  private UserMapper userMapper;
  @Resource
  private RedisCache redisCache;
  
  public User getUserById(int userId) {
    String cache_key = RedisCache.CAHCENAME+"|getUserById"+userId;
    User user = redisCache.getCache(cache_key, User.class);
    if(user != null){
      log.info("get cache with key:"+cache_key);
    }else {
      user = userMapper.selectByPrimaryKey(userId);
      redisCache.putCacheWithExpireTime(cache_key, user, RedisCache.CAHCETIME);
      log.info("put cache with key:"+cache_key);
    }
    return user;
  }
}
当系统获取用户信息时,先从缓存中查找,如果缓存中由数据便直接返回,如果没有便从数据库中获取,并将结果存入到缓存中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值