Spring4.*+Redis整合使用

Redis大家都耳熟能详,怎么使用我没太多发言权,14年就接触使用了redis,当时作为一个小菜鸟,沿用公司封装的redis做了一个redis定义规划使用,4年后当重新来看redis的时候,发现自己还是一知半解,结合网上的资料,总算是可以用了,但是个人觉得问题还诸多,先记录一下吧。

                                                                                                                                假装是前言

时下我仍然还是喜欢用maven作为项目管理工具,我比较喜欢这样的配置风格,再加上使用了很多年了,相对来说更熟悉。(现在有个叫gradle的,大家有兴趣的可以了解一下)

一、配置篇

1.增加redis的相关maven配置

	<!-- redis -->  
	<dependency>  
	    <groupId>org.springframework.data</groupId>  
	    <artifactId>spring-data-redis</artifactId>  
	    <version>1.6.0.RELEASE</version>  
	</dependency>  
	<dependency>
	    <groupId>redis.clients</groupId>  
	    <artifactId>jedis</artifactId>  
	    <version>2.7.3</version>  
	</dependency>  
	<!-- redis end --> 

这个jedis的版本似乎有点要求,和不同的spring版本搭配有点差别,我这里的spring版本是 4.3.9.RELEASE

2.增加Redis工具类RedisCacheUtil

package 你的包路径;
import java.io.ByteArrayInputStream;  
import java.io.ByteArrayOutputStream;  
import java.io.IOException;  
import java.io.ObjectInputStream;  
import java.io.ObjectOutputStream;  
  
import java.util.concurrent.Callable;

import org.springframework.cache.Cache;  
import org.springframework.cache.support.SimpleValueWrapper;  
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;  
 
/**
 * Redis操作工具类
 * @author Vin Tan
 * @date 2018年2月24日下午3:15:13
 */
public class RedisCacheUtil implements Cache{  
  
    private RedisTemplate<String, Object> redisTemplate;    
    private String name;    
    public RedisTemplate<String, Object> getRedisTemplate() {  
        return redisTemplate;    
    }  
       
    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {  
        this.redisTemplate = redisTemplate;    
    }  
       
    public void setName(String name) {  
        this.name = name;    
    }  
       
    @Override    
    public String getName() {  
        return this.name;    
    }  
  
    @Override    
    public Object getNativeCache() {  
        return this.redisTemplate;    
    }  
   
    @Override    
    public ValueWrapper get(Object key) {  
      System.out.println("get key");  
      final String keyf =  key.toString();  
      Object object = null;  
      object = redisTemplate.execute(new RedisCallback<Object>() {  
      public Object doInRedis(RedisConnection connection)    
                  throws DataAccessException {  
          byte[] key = keyf.getBytes();  
          byte[] value = connection.get(key);  
          if (value == null) {  
             return null;  
            }  
          return toObject(value);  
          }  
       });  
        return (object != null ? new SimpleValueWrapper(object) : null);  
      }  
    
     @Override    
     public void put(Object key, Object value) {  
       System.out.println("put key");  
       final String keyf = key.toString();    
       final Object valuef = value;    
       final long liveTime = 86400;    
       redisTemplate.execute(new RedisCallback<Long>() {    
           public Long doInRedis(RedisConnection connection)    
                   throws DataAccessException {    
                byte[] keyb = keyf.getBytes();    
                byte[] valueb = toByteArray(valuef);    
                connection.set(keyb, valueb);    
                if (liveTime > 0) {    
                    connection.expire(keyb, liveTime);    
                 }    
                return 1L;    
             }    
         });    
      }  
  
      private byte[] toByteArray(Object obj) {    
         byte[] bytes = null;    
         ByteArrayOutputStream bos = new ByteArrayOutputStream();    
         try {    
           ObjectOutputStream oos = new ObjectOutputStream(bos);    
           oos.writeObject(obj);    
           oos.flush();    
           bytes = bos.toByteArray();    
           oos.close();    
           bos.close();    
          }catch (IOException ex) {    
               ex.printStackTrace();    
          }    
          return bytes;    
        }    
  
       private Object toObject(byte[] bytes) {  
         Object obj = null;    
           try {  
               ByteArrayInputStream bis = new ByteArrayInputStream(bytes);    
               ObjectInputStream ois = new ObjectInputStream(bis);    
               obj = ois.readObject();    
               ois.close();    
               bis.close();    
           } catch (IOException ex) {    
               ex.printStackTrace();    
            } catch (ClassNotFoundException ex) {    
               ex.printStackTrace();    
            }    
            return obj;    
        }  
    
       @Override    
       public void evict(Object key) {    
         System.out.println("del key");  
         final String keyf = key.toString();    
         redisTemplate.execute(new RedisCallback<Long>() {    
         public Long doInRedis(RedisConnection connection)    
                   throws DataAccessException {    
             return connection.del(keyf.getBytes());    
            }    
          });    
        }  
   
        @Override    
        public void clear() {    
           // TODO Auto-generated method stub    
            System.out.println("clear key");  
           redisTemplate.execute(new RedisCallback<String>() {    
                public String doInRedis(RedisConnection connection)    
                        throws DataAccessException {    
                  connection.flushDb();    
                    return "ok";    
               }    
           });    
        }  
  
        @Override  
        public <T> T get(Object key, Class<T> type) {  
            // TODO Auto-generated method stub  
            return null;  
        }  
      
        @Override  
        public ValueWrapper putIfAbsent(Object key, Object value) {  
            // TODO Auto-generated method stub  
            return null;  
        }

		@Override
		public <T> T get(Object arg0, Callable<T> arg1) {
			// TODO Auto-generated method stub
			return null;
		}  
  
}  

自行修改下包路径吧,当然这个类我也是抄的,这个类主要作用就是读写删了,操作redis用的

3.增加redis属性文件redis.properties

redis.host=127.0.0.1
redis.port=6379
#一个pool最多可有多少个状态为idle(空闲)的jedis实例  
redis.maxIdle=30
redis.minIdle=6
redis.maxWait=3000
#一个pool可分配多少个jedis实例 
redis.maxTotal=2048
redis.expiration=30000

这个配置的解释就不多赘述吧,但是注意一点,不同版本的redis的这个key值有所变化,自己去发现吧

4.增加redis-Spring配置文件spring-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:cache="http://www.springframework.org/schema/cache"
	xmlns:context="http://www.springframework.org/schema/context"    
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
	 http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd
	 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd ">

   <context:property-placeholder location="classpath*:config/redis.properties" />    
   
	<!-- 启用缓存注解功能,这个是必须的,否则注解不会生效,另外,该注解一定要声明在spring主配置文件中才会生效 -->    
   <cache:annotation-driven cache-manager="cacheManager" />
   
	<!-- 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="true" />
	</bean>

	<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="poolConfig" ref="poolConfig" />
	</bean>

	<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
		<property name="connectionFactory" ref="JedisConnectionFactory" />
	</bean>
	<!-- spring自己的缓存管理器,这里定义了缓存位置名称 ,即注解中的value -->
	<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
		<property name="caches">
			<set>
				<!-- 这里可以配置多个redis -->
				<bean class="com..logic.utils.RedisCacheUtil">
					<property name="redisTemplate" ref="redisTemplate" />
					<property name="name" value="common" />
					<!-- common名称要在类或方法的注解中使用 -->
				</bean>
			</set>
		</property>
	</bean>
</beans>

注意把自己的RedisCacheUtil的包路径重新填写一下,别照抄了,你懂的。

到此该配的都配好了,按以前的做法,肯定是再把spring-redis.xml配置到web.xml中一起加载,但是我在网上看到一个帖子说那样是不行的,我也试了确实不行,说是需要把srping-redis.xml配置到主spring文件中加载才行,

所以呢,大家只需要在主spring文件中加上以下这行代码即可

<!-- 引入同文件夹下的redis属性配置文件 -->  
<import resource="spring-redis.xml"/> 

二、使用篇

接下来说下如何使用吧,使用之前,大家需要先永远redis服务器,一般都是在linux上搭建redis服务器,这块自行准备完成,不难。

14年那会我记得我用的redis是公司封装了,利用的是AOP拦截机制,切入式读写缓存,现在再看,发现想利用当时的方式已经不那么好用了,不得不感慨Spring的强大,spring耍皮,直接和cache玩注解了,作为一个研究技术不那么深的我来说,好吧,你牛皮。spring可以和各类缓存搭配使用,像Ecahe,Redis等。

关于Spring和Cahe的注解说明我这里也找了一个帖子,大家可以看看:

https://www.cnblogs.com/fashflying/p/6908028.html

整体来说,Srping提供了3种缓存注解

@Cacheable、@CacheEvict、@CachePut

用法自行看那个帖子吧,根据自身业务需求选择相应的注解即可

but,

这个注解有个很不爽的问题,在同一个类中的方法中二次调用本类中的其他方法,第二次调用的方法结果是不能被缓存的!!!WTF?这就很尴尬啊。。。(本人才疏学浅,无法理解,希望有大神给解释说明一下)

总之就是,你在一个方法中,可以缓存你第一次的结果,如果你在方法中再次调用同类中的另外的方法是不能缓存的。大概场景就是:你在一个service实现类中调用方法的时候,只能缓存第一次的结果,在该类中第二次调用的方法是不会触发缓存的。

对应的解决方案是:你在crontroller中分别调用2个不同service类的方法。

1.在serviceImpl中使用redis

@Cacheable(value="common",key="'status0'")
public String querySomeTime(Map<String, Object> map) {
	return mapper.query(map);
}

@Cacheable(value="common",key="'id_'+#userId")
public User getUser(String userId){
		
	return userMapper.getUser(userId);
}

关键就是@Cacheable注解,

value值:对应spring-redis.xml中cacheManager中配置的name。

key值:redis的key值,请保证唯一,否则会被覆盖。可以通过#参数的方式获取传入的参数作为key值

2.验证缓存

可以通过断点的方式看程序执行过程,是否是走数据库还是直接从缓存服务器取。

结合缓存服务器查看缓存数量,通过命令直接从缓存服务器获取对应的key-value。

三、总结

Redis是一个很强大的可基于内存亦可持久化的日志型、Key-Value数据库,应对大数据,大访问量的时候,它也能hold住,掌握使用redis也是一项必备技能哟。

正如前面所说,注解方式存在我说的那种弊端,按理来说,这么明显的问题应该是不应该还存在的,或许是因为我理解的不够透彻,或许是真的存在,希望后续会有所结论。同时,如果你刚好看到又恰好有这方面的经验,敬请赐教,不甚感激。

猜你喜欢

转载自my.oschina.net/gmupload/blog/1634457