在没有封装情况下使用 Java API的缺点,需要自己白那些规则把 java 对象 和 Redis 的字符串进行相互转换,而在 Spring 中这些问题都可以轻松处理。

在Spring中使用 Redis ,除了需要 jedis.jar 外,还需要下载 spring-data-redis.jar,打开网址 https://mvnrepository.com/artifact/org.springframework.data/spring-data-redis , 

就能够看到这样的页面:

值得注意的是, jar 包 和 Spring 版本兼容的问题。

注意 spring5以上需要配置 spring-data-redis 2.0

基于spring主版本为4.3.13.RELEASE的项目,测试以下对应版本可用。

spring-data-redis版本

jedis版本

备注

1.5.2.RELEASE

2.7.3

1.6.0.RELEASE

2.7.2  2.7.3

1.6.2.RELEASE

2.8.0

1.8.1.RELEASE

2.9.0

1.8.4.RELEASE

2.9.0


原有的SpringMVC配置不动,添加下面这个配置

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"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
 
 
	
     <!-- redis数据源 -->
    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
		<!-- 最大连接数 -->
		<!-- <property name="maxTotal" value="30" />
		最大空闲连接数
		<property name="maxIdle" value="10" />
		每次释放连接的最大数目
		<property name="numTestsPerEvictionRun" value="1024" />
		释放连接的扫描间隔(毫秒)
		<property name="timeBetweenEvictionRunsMillis" value="30000" />
		连接最小空闲时间
		<property name="minEvictableIdleTimeMillis" value="1800000" />
		连接空闲多久后释放, 当空闲时间>该值 且 空闲连接>最大空闲连接数 时直接释放
		<property name="softMinEvictableIdleTimeMillis" value="10000" />
		获取连接时的最大等待毫秒数,小于零:阻塞不确定的时间,默认-1
		<property name="maxWaitMillis" value="1500" />
		在获取连接的时候检查有效性, 默认false
		<property name="testOnBorrow" value="true" />
		在空闲时检查有效性, 默认false
		<property name="testWhileIdle" value="true" />
		连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
		<property name="blockWhenExhausted" value="false" /> -->
		  <property name="maxIdle" value="100" />
          <property name="minIdle" value="8" />
          <property name="maxWaitMillis" value="-1" />
         <property name="testOnBorrow" value="true" />
 
    </bean>
   <!-- Spring-redis连接池管理工厂 -->
    <bean id="connectionFactory"
        class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="poolConfig" ref="poolConfig" />
          <!-- 端口号 -->
        <property name="port" value="6379" />
         <!-- IP地址 -->
        <property name="hostName" value="427.925.2214.1279" />
         <!-- 密码 -->
        <property name="password" value="feizhou123" />
         <!-- 超时时间 -->
        <property name="timeout" value="-1" />
    </bean>
    <!-- redis操作模板,面向对象的模板 -->
    <bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer" />  
   <bean id="jdkSerializationRedisSerializer" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
    <bean id="stringRedisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
        <property name="connectionFactory" ref="connectionFactory" />
        <!-- 如果不配置Serializer,那么存储的时候只能使用String,如果用对象类型存储,那么会提示错误 -->
        <property name="keySerializer" ref="stringRedisSerializer"></property>
        <property name="valueSerializer" ref="jdkSerializationRedisSerializer"> </property>
    </bean>
    
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"  
    p:connectionFactory-ref="connectionFactory"   
    p:keySerializer-ref="stringRedisSerializer"   
    p:hashKeySerializer-ref="stringRedisSerializer" />  
</beans>

 redis.properties:

redis.host=1936.16334.23.22
redis.port=6379
redis.pass=feizhou123
redis.timeout=-1
redis.maxIdle=100
redis.minIdle=8
redis.maxWait=-1
redis.testOnBorrow=true

需要添加的jar包:

<!--配置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>
<dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-pool2</artifactId>
            <version>2.3</version>
       </dependency>
<dependency>
		    <groupId>commons-pool</groupId>
		    <artifactId>commons-pool</artifactId>
		    <version>1.5.5</version>
		</dependency>

工具类:

package com.feizhou.commonService.redis;
 
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
 
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.feizhou.common.tools.commonTools.JsonUtil;
 
/**
 * 通用缓存工具类
 * 
 * @author lh
 * @version 3.0
 * @since 2016-6-22
 * 
 */
@Component
public class CacheUtils {
	@Resource
	private   StringRedisTemplate stringRedisTemplate;
	@Resource
	private   RedisTemplate<String, Object> redisTemplate;
 
	/**
	 * 删除缓存<br>
	 * 根据key精确匹配删除
	 * 
	 * @param key
	 */
	@SuppressWarnings("unchecked")
	public   void del(String... key) {
		if (key != null && key.length > 0) {
			if (key.length == 1) {
				redisTemplate.delete(key[0]);
			} else {
				redisTemplate.delete(CollectionUtils.arrayToList(key));
			}
		}
	}
	/**
	 * 
	 * @Description (根据key精确匹配删除)
	 * @author feizhou
	 * @Date 2018年5月29日下午5:39:06  
	 * @version 1.0.0
	 * @param key
	 */
	public   void deleteByKey(String  key) {
		if (key != null) {
			redisTemplate.delete(key);
		}
	}
 
	/**
	 * 批量删除<br>
	 * (该操作会执行模糊查询,请尽量不要使用,以免影响性能或误删)
	 * 
	 * @param pattern
	 */
	public  void batchDel(String... pattern) {
		for (String kp : pattern) {
			redisTemplate.delete(redisTemplate.keys(kp + "*"));
		}
	}
 
	/**
	 * 取得缓存(int型)
	 * 
	 * @param key
	 * @return
	 */
	public  Integer getInt(String key) {
		String value = stringRedisTemplate.boundValueOps(key).get();
		if (StringUtils.isNotEmpty(value)) {
			return Integer.valueOf(value);
		}
		return null;
	}
 
	/**
	 * 取得缓存(字符串类型)
	 * 
	 * @param key
	 * @return
	 */
	public  String getStr(String key) {
		return stringRedisTemplate.boundValueOps(key).get();
	}
 
	/**
	 * 取得缓存(字符串类型)
	 * 
	 * @param key
	 * @return
	 */
	public  String getStr(String key, boolean retain) {
		String value = stringRedisTemplate.boundValueOps(key).get();
		if (!retain) {
			redisTemplate.delete(key);
		}
		return value;
	}
 
	/**
	 * 获取缓存<br>
	 * 注:基本数据类型(Character除外),请直接使用get(String key, Class<T> clazz)取值
	 * 
	 * @param key
	 * @return
	 */
	public  Object getObj(String key) {
		return redisTemplate.boundValueOps(key).get();
	}
 
	/**
	 * 获取缓存<br>
	 * 注:java 8种基本类型的数据请直接使用get(String key, Class<T> clazz)取值
	 * 
	 * @param key
	 * @param retain
	 *            是否保留
	 * @return
	 */
	public  Object getObj(String key, boolean retain) {
		Object obj = redisTemplate.boundValueOps(key).get();
		if (!retain) {
			redisTemplate.delete(key);
		}
		return obj;
	}
 
	/**
	 * 获取缓存<br>
	 * 注:该方法暂不支持Character数据类型
	 * 
	 * @param key
	 *            key
	 * @param clazz
	 *            类型
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public  <T> T get(String key, Class<T> clazz) {
		return (T) redisTemplate.boundValueOps(key).get();
	}
 
	/**
	 * 获取缓存json对象<br>
	 * 
	 * @param key
	 *            key
	 * @param clazz
	 *            类型
	 * @return
	 * @throws Exception 
	 */
	@SuppressWarnings("unchecked")
	public  <T> T getJson(String key, Class<T> clazz) throws Exception {
		String jsonStr=null;
		jsonStr=stringRedisTemplate.boundValueOps(key).get();
		if(jsonStr==null){
			return null;
		}else{
			return (T) JsonUtil.jsonToBean(jsonStr, clazz);
		}
	}
 
	/**
	 * 将value对象写入缓存
	 * 
	 * @param key
	 * @param value
	 * @param time
	 *            失效时间(秒)
	 */
	public  void set(String key, Object value, Long time) {
		if (value.getClass().equals(String.class)) {
			stringRedisTemplate.opsForValue().set(key, value.toString());
		} else if (value.getClass().equals(Integer.class)) {
			stringRedisTemplate.opsForValue().set(key, value.toString());
		} else if (value.getClass().equals(Double.class)) {
			stringRedisTemplate.opsForValue().set(key, value.toString());
		} else if (value.getClass().equals(Float.class)) {
			stringRedisTemplate.opsForValue().set(key, value.toString());
		} else if (value.getClass().equals(Short.class)) {
			stringRedisTemplate.opsForValue().set(key, value.toString());
		} else if (value.getClass().equals(Long.class)) {
			stringRedisTemplate.opsForValue().set(key, value.toString());
		} else if (value.getClass().equals(Boolean.class)) {
			stringRedisTemplate.opsForValue().set(key, value.toString());
		} else {
			redisTemplate.opsForValue().set(key, value);
		}
		if (time != null && time > 0) {
            redisTemplate.expire(key, time, TimeUnit.SECONDS);
            stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);
        }
	}
 
	/**
	 * 将value对象以JSON格式写入缓存
	 * 
	 * @param key
	 * @param value
	 * @param time
	 *            失效时间(秒)
	 */
	public  void setJson(String key, Object value, Long time) {
		stringRedisTemplate.opsForValue().set(key, JsonUtil.toJsonString(value));
		if (time!=null&&time > 0) {
			stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);
		}
	}
 
	/**
	 * 更新key对象field的值
	 * 
	 * @param key
	 *            缓存key
	 * @param field
	 *            缓存对象field
	 * @param value
	 *            缓存对象field值
	 */
	public  void setJsonField(String key, String field, String value) {
		JSONObject obj = JSON.parseObject(stringRedisTemplate.boundValueOps(key).get());
		obj.put(field, value);
		stringRedisTemplate.opsForValue().set(key, obj.toJSONString());
	}
 
	/**
	 * 递减操作
	 * 
	 * @param key
	 * @param by
	 * @return
	 */
	public  double decr(String key, double by) {
		return redisTemplate.opsForValue().increment(key, -by);
	}
 
	/**
	 * 递增操作
	 * 
	 * @param key
	 * @param by
	 * @return
	 */
	public  double incr(String key, double by) {
		return redisTemplate.opsForValue().increment(key, by);
	}
 
	/**
	 * 获取double类型值
	 * 
	 * @param key
	 * @return
	 */
	public  double getDouble(String key) {
		String value = stringRedisTemplate.boundValueOps(key).get();
		if (StringUtils.isNotBlank(value)) {
			return Double.valueOf(value);
		}
		return 0d;
	}
 
	/**
	 * 设置double类型值
	 * 
	 * @param key
	 * @param value
	 * @param time
	 *            失效时间(秒)
	 */
	public  void setDouble(String key, double value, Long time) {
		stringRedisTemplate.opsForValue().set(key, String.valueOf(value));
		if (time!=null&&time > 0) {
			stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);
		}
	}
 
	/**
	 * 设置double类型值
	 * 
	 * @param key
	 * @param value
	 * @param time
	 *            失效时间(秒)
	 */
	public  void setInt(String key, int value, Long time) {
		stringRedisTemplate.opsForValue().set(key, String.valueOf(value));
		if (time!=null&&time > 0) {
			stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);
		}
	}
 
	/**
	 * 将map写入缓存
	 * 
	 * @param key
	 * @param map
	 * @param time
	 *            失效时间(秒)
	 */
	public  <T> void setMap(String key, Map<String, T> map, Long time) {
		redisTemplate.opsForHash().putAll(key, map);
	}
 
	/**
	 * 将map写入缓存
	 * 
	 * @param key
	 * @param map
	 * @param time
	 *            失效时间(秒)
	 */
	@SuppressWarnings("unchecked")
	public  <T> void setMap(String key, T obj, Long time) {
		Map<String, String> map = (Map<String, String>)JsonUtil.parseObject(obj, Map.class);
		redisTemplate.opsForHash().putAll(key, map);
	}
 
	/**
	 * 向key对应的map中添加缓存对象
	 * 
	 * @param key
	 * @param map
	 */
	public  <T> void addMap(String key, Map<String, T> map) {
		redisTemplate.opsForHash().putAll(key, map);
	}
 
	/**
	 * 向key对应的map中添加缓存对象
	 * 
	 * @param key
	 *            cache对象key
	 * @param field
	 *            map对应的key
	 * @param value
	 *            值
	 */
	public  void addMap(String key, String field, String value) {
		redisTemplate.opsForHash().put(key, field, value);
	}
 
	/**
	 * 向key对应的map中添加缓存对象
	 * 
	 * @param key
	 *            cache对象key
	 * @param field
	 *            map对应的key
	 * @param obj
	 *            对象
	 */
	public  <T> void addMap(String key, String field, T obj) {
		redisTemplate.opsForHash().put(key, field, obj);
	}
 
	/**
	 * 获取map缓存
	 * 
	 * @param key
	 * @param clazz
	 * @return
	 */
	public  <T> Map<String, T> mget(String key, Class<T> clazz) {
		BoundHashOperations<String, String, T> boundHashOperations = redisTemplate.boundHashOps(key);
		return boundHashOperations.entries();
	}
 
	/**
	 * 获取map缓存中的某个对象
	 * 
	 * @param key
	 * @param field
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public  <T> T getMapField(String key, String field, Class<T> clazz) {
		return (T) redisTemplate.boundHashOps(key).get(field);
	}
 
		/**
		 * 获取map缓存
		 * 
		 * @param key
		 * @param clazz
		 * @return
		 */
		public  <T> T getMap(String key, Class<T> clazz) {
			BoundHashOperations<String, String, String> boundHashOperations = redisTemplate.boundHashOps(key);
			Map<String, String> map = boundHashOperations.entries();
			return JsonUtil.parseObject(map, clazz);
		}
	
		/**
	 * 删除map中的某个对象
	 * 
	 * @author lh
	 * @date 2016年8月10日
	 * @param key
	 *            map对应的key
	 * @param field
	 *            map中该对象的key
	 */
	public void delMapField(String key, String... field) {
		BoundHashOperations<String, String, ?> boundHashOperations = redisTemplate.boundHashOps(key);
		boundHashOperations.delete(field);
	}
 
	/**
	 * 指定缓存的失效时间
	 * 
	 * @author FangJun
	 * @date 2016年8月14日
	 * @param key
	 *            缓存KEY
	 * @param time
	 *            失效时间(秒)
	 */
	public  void expire(String key, Long time) {
		if (time!=null&&time > 0) {
			redisTemplate.expire(key, time, TimeUnit.SECONDS);
		}
	}
 
	/**
	 * 添加set
	 * 
	 * @param key
	 * @param value
	 */
	public  void sadd(String key, String... value) {
		redisTemplate.boundSetOps(key).add(value);
	}
 
	/**
	 * 删除set集合中的对象
	 * 
	 * @param key
	 * @param value
	 */
	public  void srem(String key, String... value) {
		redisTemplate.boundSetOps(key).remove(value);
	}
 
	/**
	 * set重命名
	 * 
	 * @param oldkey
	 * @param newkey
	 */
	public  void srename(String oldkey, String newkey) {
		redisTemplate.boundSetOps(oldkey).rename(newkey);
	}
 
	/**
	 * 短信缓存
	 * 
	 * @author fxl
	 * @date 2016年9月11日
	 * @param key
	 * @param value
	 * @param time
	 */
	public  void setIntForPhone(String key, Object value, int time) {
		stringRedisTemplate.opsForValue().set(key, JsonUtil.toJsonString(value));
		if (time > 0) {
			stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);
		}
	}
 
	/**
	 * 模糊查询keys
	 * 
	 * @param pattern
	 * @return
	 */
	public  Set<String> keys(String pattern) {
		return redisTemplate.keys(pattern);
	}
	
	/**
	 * 
	 * @Description (检查key是否存在,返回boolean值 )
	 * @author feizhou
	 * @Date 2018年5月29日下午5:37:40  
	 * @version 1.0.0
	 * @param key
	 * @return
	 */
	public  Boolean   ishasKey(String key) {
		return stringRedisTemplate.hasKey(key);
	}
 
 
 
}

————————————————
版权声明:本文为CSDN博主「单身贵族男」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/zhou920786312/article/details/82496406

 注意 spring5以上需要配置 spring-data-redis 2.0

项目中配置:

jar包:

  <!-- spring redis配置: 注意 spring5以上需要配置 spring-data-redis 2.0 -->
    <!-- https://docs.spring.io/spring-data/redis/docs/2.2.12.RELEASE/reference/html/#new-features  -->
    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-redis</artifactId>
      <version>2.0.0.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>2.9.0</version>
    </dependency>
applicationContext.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:aop="http://www.springframework.org/schema/aop"   
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:cache="http://www.springframework.org/schema/cache"
    xmlns:jee="http://www.springframework.org/schema/jee"  
    xmlns:tx="http://www.springframework.org/schema/tx"  
    xsi:schemaLocation="    
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd  
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd  
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">    
        
    <!--  配置数据源 SQLServer  -->
   
    <!--
    <context:property-placeholder location="classpath:jdbc.properties" ignore-resource-not-found="true" ></context:property-placeholder>
    -->

    <!--
	  导入配置文件 config.properties 、redis.properties
	  注意:如果项目中有多个属性文件,要合并在一起加载同一管理。如果分散在不同的配置文件中,只能按文件顺序加载第一个配置文件中的属性文件。
	  <context:property-placeholder location="classpath*:config.properties"></context:property-placeholder>
	-->
    <context:property-placeholder location="classpath*:*.properties"></context:property-placeholder>

    
    <!-- 配置数据库 gzxf -->
    <bean id="dataSource"
		class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}" />
		<property name="url" value="${jdbc.url}"/>
		<property name="username" value="${jdbc.username}"/>
		<property name="password" value="${jdbc.password}"/>
        <!-- 配置初始化大小、bai最小、最大 -->
        <property name="initialSize" value="1" />
        <property name="minIdle" value="1" />
        <property name="maxActive" value="20" />
        <!-- 配置获取连接等待超时的时间 -->
        <property name="maxWait" value="60000" />
        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="300000" />
        <property name="validationQuery" value="SELECT 'x'" />
        <property name="testWhileIdle" value="true" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />
        <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
        <property name="poolPreparedStatements" value="true" />
        <property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
        <!-- 配置监控统计拦截的filters,去掉后监控界面sql无法统计 -->
        <property name="filters" value="stat" />
	</bean>
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="mapperLocations" value="classpath:/mapper/*.xml"></property>
		<property name="configLocation" value="classpath:mybatis-config.xml"></property>
        <!-- 配置分页插件 -->
        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageInterceptor">
                    <property name="properties">
                        <value>
                            helperDialect=sqlserver2012
                            reasonable=true
                        </value>
                    </property>
                </bean>
            </array>
        </property>
	</bean>
    <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.dao"></property>
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
	</bean>

    <!-- 开启注解: 自动扫描 -->
    <context:annotation-config></context:annotation-config>

    <!-- 配置事务(注解方式) -->
    <!-- 使用Annotation自动注册Bean,解决事物失效问题:在主容器中不扫描@Controller注解,在SpringMvc中只扫描@Controller注解。  -->
    <context:component-scan base-package="com.service"><!-- base-package 如果多个,用“,”分隔 -->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!-- 定义事务 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 配置 Annotation 驱动,扫描@Transactional注解的类定义事务  -->
    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
    <!-- MyBatis end -->

    <!-- 添加redis工具类 -->
    <import resource="classpath:applicationContext-redis.xml" />

    <!-- 添加spring工具类 -->
    <bean id="springUtil" class="com.fire.oms.api.utils.SpringUtil" lazy-init="false" />
	
</beans>

applicationContext-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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:context="http://www.springframework.org/schema/context" 
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

	<description>Redis configuration</description>

	<!-- 载入redis配置参数 -->
	<!-- <context:property-placeholder location="classpath:redis.properties" ignore-unresolvable="true" /> -->

	<!-- redis config start -->
	<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
		<property name="maxIdle" value="${redis.pool.maxIdle}"></property>
		<property name="maxTotal" value="${redis.pool.maxActive}" />
		<property name="maxWaitMillis" value="${redis.pool.maxWaitMillis}" />
		<property name="testOnBorrow" value="${redis.pool.testOnBorrow}" />
		<!--
        <property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}"></property>
        <property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}"></property>
        <property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}"></property>
        -->
	</bean>

	<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" destroy-method="destroy">
		<property name="poolConfig" ref="jedisPoolConfig"></property>
		<property name="hostName" value="${redis.host}"></property>
		<property name="port" value="${redis.port}"></property>
		<!-- 通过密码连接服务器(保证安全) -->
		<property name="password" value="${redis.password}"></property>
		<property name="timeout" value="${redis.timeout}"></property>
		<!--是否使用連接池 <property name="usePool" value="${redis.usePool}"></property> -->
	</bean>

	<!-- redis操作模板,面向对象的模板 -->
	<bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer" />
	<bean id="jdkSerializationRedisSerializer" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
	<bean id="stringRedisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
		<property name="connectionFactory" ref="jedisConnectionFactory" />
		<!-- 如果不配置Serializer,那么存储的时候只能使用String,如果用对象类型存储,那么会提示错误 -->
		<!-- 注意:原来valueSerializer配置为jdkSerializationRedisSerializer , 实际测试取值时会出现类似内容: \xac\xed\x00\x05t\x00\tb ,需要改成stringRedisSerializer    -->
		<property name="keySerializer" ref="stringRedisSerializer" />
		<property name="valueSerializer" ref="stringRedisSerializer" />
	</bean>

	<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
		<property name="connectionFactory" ref="jedisConnectionFactory" />
		<property name="keySerializer">
			<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
		</property>
		<property name="valueSerializer">
			<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
		</property>
	</bean>
	<!-- redis config end -->

	<!-- Redis 发布订阅监配置 -->
	<!-- 1、配置监听类 -->
	<bean id="redisMessageListener" class="com.fire.oms.api.listener.RedisMessageListener"></bean>
	<!-- 2、配置监听容器 -->
	<bean id="topicContainer" class="org.springframework.data.redis.listener.RedisMessageListenerContainer" destroy-method="destroy">

		<!-- redis连接工厂 -->
		<property name="connectionFactory" ref="jedisConnectionFactory"></property>
		<!-- 连接池,这里要线程池生存,才能继续监听 -->
		<property name="taskExecutor">
			<bean class="org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler">
				<property name="poolSize" value="3"></property>
			</bean>
		</property>

		<!-- 监听消息map -->
		<property name="messageListeners">
			<map>
				<!-- 配置监听者,key-ref 和 bean id 定义一直 -->
				<entry key-ref="redisMessageListener">
					<!-- 监听类 -->
					<bean class="org.springframework.data.redis.listener.ChannelTopic" >
						<constructor-arg value="message"></constructor-arg>
					</bean>
				</entry>
			</map>
		</property>
	</bean>


</beans>

redis.properties:

#redis pool config
redis.pool.maxActive=1000
redis.pool.maxIdle=100
redis.pool.maxWaitMillis=10000
redis.pool.testOnBorrow=true

#redis config
redis.host=127.0.0.1
redis.port=6379
redis.timeout=6000
redis.password=123456
redis.dbindex=8
redis.usePool=1
redis.default.expire=1800000
Redis 缓存工具类:CacheUtils
package com.utils;

import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Redis 缓存工具类
 */
public class CacheUtils {

    /** redis操作模板,面向对象的模板 */
    private static StringRedisTemplate stringRedisTemplate
            = (StringRedisTemplate) SpringUtil.getBean("stringRedisTemplate");
    private static RedisTemplate<String, Object> redisTemplate
            = (RedisTemplate) SpringUtil.getBean("redisTemplate");

    /**
     * 删除缓存<br>
     * 根据key精确匹配删除
     *
     * @param key
     */
    @SuppressWarnings("unchecked")
    public static void del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete(CollectionUtils.arrayToList(key));
            }
        }
    }

    /**
     * (根据key精确匹配删除)
     * @param key
     */
    public static void deleteByKey(String  key) {
        if (key != null) {
            redisTemplate.delete(key);
        }
    }

    /**
     * 批量删除<br>
     * (该操作会执行模糊查询,请尽量不要使用,以免影响性能或误删)
     *
     * @param pattern
     */
    public void batchDel(String... pattern) {
        for (String kp : pattern) {
            redisTemplate.delete(redisTemplate.keys(kp + "*"));
        }
    }

    /**
     * 取得缓存(int型)
     *
     * @param key
     * @return
     */
    public  Integer getInt(String key) {
        String value = stringRedisTemplate.boundValueOps(key).get();
        if (StringUtils.isNotEmpty(value)) {
            return Integer.valueOf(value);
        }
        return null;
    }

    /**
     * 取得缓存(字符串类型)
     *
     * @param key
     * @return
     */
    public static String getStr(String key) {
        return stringRedisTemplate.boundValueOps(key).get();
    }

    /**
     * 取得缓存(字符串类型)
     *
     * @param key
     * @return
     */
    public static String getStr(String key, boolean retain) {
        String value = stringRedisTemplate.boundValueOps(key).get();
        if (!retain) {
            redisTemplate.delete(key);
        }
        return value;
    }

    /**
     * 获取缓存<br>
     * 注:基本数据类型(Character除外),请直接使用get(String key, Class<T> clazz)取值
     *
     * @param key
     * @return
     */
    public static Object getObj(String key) {
        return redisTemplate.boundValueOps(key).get();
    }

    /**
     * 获取缓存<br>
     * 注:java 8种基本类型的数据请直接使用get(String key, Class<T> clazz)取值
     *
     * @param key
     * @param retain
     *            是否保留
     * @return
     */
    public  Object getObj(String key, boolean retain) {
        Object obj = redisTemplate.boundValueOps(key).get();
        if (!retain) {
            redisTemplate.delete(key);
        }
        return obj;
    }

    /**
     * 获取缓存<br>
     * 注:该方法暂不支持Character数据类型
     *
     * @param key
     *            key
     * @param clazz
     *            类型
     * @return
     */
    @SuppressWarnings("unchecked")
    public  <T> T get(String key, Class<T> clazz) {

        return (T) redisTemplate.boundValueOps(key).get();
    }

    /**
     * 获取缓存json对象<br>
     *
     * @param key
     *            key
     * @param clazz
     *            类型
     * @return
     * @throws Exception

    @SuppressWarnings("unchecked")
    public  <T> T getJson(String key, Class<T> clazz) throws Exception {
        String jsonStr=null;
        jsonStr=stringRedisTemplate.boundValueOps(key).get();
        if(jsonStr==null){
            return null;
        }else{
            return (T) JsonUtil.jsonToBean(jsonStr, clazz);
        }
    } */

    /**
     * 将value对象写入缓存
     *
     * @param key
     * @param value
     * @param time
     *            失效时间(秒)
     */
    public static void set(String key, Object value, Long time) {
        if (value.getClass().equals(String.class)) {
            stringRedisTemplate.opsForValue().set(key, value.toString());
        } else if (value.getClass().equals(Integer.class)) {
            stringRedisTemplate.opsForValue().set(key, value.toString());
        } else if (value.getClass().equals(Double.class)) {
            stringRedisTemplate.opsForValue().set(key, value.toString());
        } else if (value.getClass().equals(Float.class)) {
            stringRedisTemplate.opsForValue().set(key, value.toString());
        } else if (value.getClass().equals(Short.class)) {
            stringRedisTemplate.opsForValue().set(key, value.toString());
        } else if (value.getClass().equals(Long.class)) {
            stringRedisTemplate.opsForValue().set(key, value.toString());
        } else if (value.getClass().equals(Boolean.class)) {
            stringRedisTemplate.opsForValue().set(key, value.toString());
        } else {
            redisTemplate.opsForValue().set(key, value);
        }
        if (time != null && time > 0) {
            redisTemplate.expire(key, time, TimeUnit.SECONDS);
        }
    }

    /**
     * 将value对象以JSON格式写入缓存
     *
     * @param key
     * @param value
     * @param time
     *            失效时间(秒)

    public  void setJson(String key, Object value, Long time) {
        stringRedisTemplate.opsForValue().set(key, JsonUtil.toJsonString(value));
        if (time!=null&&time > 0) {
            stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);
        }
    }
     */

    /**
     * 更新key对象field的值
     *
     * @param key
     *            缓存key
     * @param field
     *            缓存对象field
     * @param value
     *            缓存对象field值

    public  void setJsonField(String key, String field, String value) {
        JSONObject obj = JSON.parseObject(stringRedisTemplate.boundValueOps(key).get());
        obj.put(field, value);
        stringRedisTemplate.opsForValue().set(key, obj.toJSONString());
    }
     */

    /**
     * 递减操作
     *
     * @param key
     * @param by
     * @return
     */
    public  double decr(String key, double by) {
        return redisTemplate.opsForValue().increment(key, -by);
    }

    /**
     * 递增操作
     *
     * @param key
     * @param by
     * @return
     */
    public  double incr(String key, double by) {
        return redisTemplate.opsForValue().increment(key, by);
    }

    /**
     * 获取double类型值
     *
     * @param key
     * @return
     */
    public  double getDouble(String key) {
        String value = stringRedisTemplate.boundValueOps(key).get();
        if (StringUtils.isNotBlank(value)) {
            return Double.valueOf(value);
        }
        return 0d;
    }

    /**
     * 设置double类型值
     *
     * @param key
     * @param value
     * @param time
     *            失效时间(秒)
     */
    public  void setDouble(String key, double value, Long time) {
        stringRedisTemplate.opsForValue().set(key, String.valueOf(value));
        if (time!=null&&time > 0) {
            stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);
        }
    }

    /**
     * 设置double类型值
     *
     * @param key
     * @param value
     * @param time
     *            失效时间(秒)
     */
    public  void setInt(String key, int value, Long time) {
        stringRedisTemplate.opsForValue().set(key, String.valueOf(value));
        if (time!=null&&time > 0) {
            stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);
        }
    }

    /**
     * 将map写入缓存
     *
     * @param key
     * @param map
     * @param time
     *            失效时间(秒)
     */
    public  <T> void setMap(String key, Map<String, T> map, Long time) {
        redisTemplate.opsForHash().putAll(key, map);
    }

    /**
     * 将map写入缓存
     *
     * @param key
     * @param map
     * @param time
     *            失效时间(秒)

    @SuppressWarnings("unchecked")
    public  <T> void setMap(String key, T obj, Long time) {
        Map<String, String> map = (Map<String, String>)JsonUtil.parseObject(obj, Map.class);
        redisTemplate.opsForHash().putAll(key, map);
    }
     */

    /**
     * 向key对应的map中添加缓存对象
     *
     * @param key
     * @param map
     */
    public  <T> void addMap(String key, Map<String, T> map) {
        redisTemplate.opsForHash().putAll(key, map);
    }

    /**
     * 向key对应的map中添加缓存对象
     *
     * @param key
     *            cache对象key
     * @param field
     *            map对应的key
     * @param value
     *            值
     */
    public  void addMap(String key, String field, String value) {
        redisTemplate.opsForHash().put(key, field, value);
    }

    /**
     * 向key对应的map中添加缓存对象
     *
     * @param key
     *            cache对象key
     * @param field
     *            map对应的key
     * @param obj
     *            对象
     */
    public  <T> void addMap(String key, String field, T obj) {
        redisTemplate.opsForHash().put(key, field, obj);
    }

    /**
     * 获取map缓存
     *
     * @param key
     * @param clazz
     * @return

    public  <T> Map<String, T> mget(String key, Class<T> clazz) {
        BoundHashOperations<String, String, T> boundHashOperations = redisTemplate.boundHashOps(key);
        return boundHashOperations.entries();
    }*/

    /**
     * 获取map缓存中的某个对象
     *
     * @param key
     * @param field
     * @param clazz
     * @return
     */
    @SuppressWarnings("unchecked")
    public  <T> T getMapField(String key, String field, Class<T> clazz) {
        return (T) redisTemplate.boundHashOps(key).get(field);
    }

    /**
     * 获取map缓存
     *
     * @param key
     * @param clazz
     * @return

    public  <T> T getMap(String key, Class<T> clazz) {
        BoundHashOperations<String, String, String> boundHashOperations = redisTemplate.boundHashOps(key);
        Map<String, String> map = boundHashOperations.entries();
        return JsonUtil.parseObject(map, clazz);
    } */

    /**
     * 删除map中的某个对象
     *
     * @author lh
     * @date 2016年8月10日
     * @param key
     *            map对应的key
     * @param field
     *            map中该对象的key
     */
    public void delMapField(String key, String... field) {
        BoundHashOperations<String, String, ?> boundHashOperations = redisTemplate.boundHashOps(key);
        boundHashOperations.delete(field);
    }

    /**
     * 指定缓存的失效时间
     *
     * @author FangJun
     * @date 2016年8月14日
     * @param key
     *            缓存KEY
     * @param time
     *            失效时间(秒)
     */
    public  void expire(String key, Long time) {
        if (time!=null&&time > 0) {
            redisTemplate.expire(key, time, TimeUnit.SECONDS);
        }
    }

    /**
     * 添加set
     *
     * @param key
     * @param value
     */
    public  void sadd(String key, String... value) {
        redisTemplate.boundSetOps(key).add(value);
    }

    /**
     * 删除set集合中的对象
     *
     * @param key
     * @param value
     */
    public  void srem(String key, String... value) {
        redisTemplate.boundSetOps(key).remove(value);
    }

    /**
     * set重命名
     *
     * @param oldkey
     * @param newkey
     */
    public  void srename(String oldkey, String newkey) {
        redisTemplate.boundSetOps(oldkey).rename(newkey);
    }

    /**
     * 短信缓存
     *
     * @author fxl
     * @date 2016年9月11日
     * @param key
     * @param value
     * @param time

    public  void setIntForPhone(String key, Object value, int time) {
        stringRedisTemplate.opsForValue().set(key, JsonUtil.toJsonString(value));
        if (time > 0) {
            stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);
        }
    }
     */

    /**
     * 模糊查询keys
     *
     * @param pattern
     * @return
     */
    public static Set<String> keys(String pattern) {

        return redisTemplate.keys(pattern);
    }

    /**
     *
     * @Description (检查key是否存在,返回boolean值 )
     * @author feizhou
     * @Date 2018年5月29日下午5:37:40
     * @version 1.0.0
     * @param key
     * @return
     */
    public  Boolean   ishasKey(String key) {
        return stringRedisTemplate.hasKey(key);
    }

}

SpringUtil类:

package com.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 工具类 - Spring
 * @author zgp2010
 *
 */

public class SpringUtil implements ApplicationContextAware {
	
	private static ApplicationContext applicationContext;

	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		SpringUtil.applicationContext = applicationContext;
	}

	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	/**
	 * 根据Bean名称获取实例
	 * 
	 * @param name
	 *            Bean注册名称
	 * 
	 * @return bean实例
	 * 
	 * @throws BeansException
	 */
	public static Object getBean(String name) throws BeansException {
		return applicationContext.getBean(name);
	}
}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐