redis.properties

连接 Redis 服务器的相关信息

#ip地址
redis.hostName=127.0.0.1
#端口号
redis.port=6379
#登录密码
redis.password=123456
#客户端超时时间单位是毫秒 默认是2000
redis.timeout=2000

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

applicationContext.xml

配置连接池,连接工厂等,以上都是为了RedisTemplate 服务,这个类就提供常用的访问 Redis的方法。
然后又把这个 RedisTemplate 类的实例,注入到 RedisUtil 工具类里,方便调用

<?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:property-placeholder location="classpath:*.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" 
		p:connection-factory-ref="jedisConnectionFactory" >
		<property name="keySerializer">
			<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
		</property>
		<property name="hashKeySerializer">
			<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
		</property>
		<property name="valueSerializer">
			<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>			
		</property>
		<property name="hashValueSerializer">
			<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
		</property>				
	</bean>
	
	<!-- 自定义redis工具类,在需要缓存的地方注入此类 -->
	<bean id="redisUtil" class="com.icomac.RedisUtil">
		<property name="redisTemplate" ref="redisTemplate"/>
	</bean>                      
</beans>

RedisUtil

RedisUtil 工具类,封装了 RedisTemplate 这个类,以提供更为便利的 对于 Redis 的访问

这个类针对了四种数据类型即String、List、Map、Set,我不展示所有的代码,只提取一些测试类中调用的方法

/**
	 * 删除缓存
	 * @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));
			}
		}
	}

//===============================String==========================
	/**
	 * 普通缓存获取
	 * @param key键
	 * @return 值
	 */
	public Object get(String key) {
		return key == null ? null : redisTemplate.opsForValue().get(key);
	}
	
	/**
	 * 普通缓存放入
	 * @param key键
	 * @param value值
	 * @return true成功 false失败
	 */
	public boolean set(String key, Object value) {
		try {
			redisTemplate.opsForValue().set(key, value);
			return true;
		} catch (Exception e) {
			// TODO: handle exception
			return false;
		}
	}
	
	/**
	 * 递增
	 * @param key键
	 * @param by 要增加几(大于0)
	 * @return
	 */
	public long incr(String key, long delta) {
		if (delta < 0) {
			throw new RuntimeException("递增因子必须大于0");
		}
		return redisTemplate.opsForValue().increment(key, delta);
	}
	
	/**
	 * 递减
	 * @param key键
	 * @param by 要减少几(小于0)
	 * @return
	 */
	public long decr(String key, long delta) {
		if (delta < 0) {
			throw new RuntimeException("递减因子必须大于0");
		}
		return redisTemplate.opsForValue().increment(key, -delta);
	}
	
//========================================Map=============================
	/**
	 * HashGet
	 * @param key 键不能为null
	 * @param item 项不能为null
	 * @return 值
	 */
	public Object hget(String key, String item) {
		return redisTemplate.opsForHash().get(key, item);
	}
	
	/**
	 * 获取hashKey对应的所有键值
	 * @param key键
	 * @return 对应的多个键值
	 */
	public Map<Object, Object> hmget(String key){
		return redisTemplate.opsForHash().entries(key);
	}
	
	/**
	 * HashSet
	 * @param key键
	 * @param map对应多个键值
	 * @return true 成功  false 失败
	 */
	public boolean hmset(String key, Map<String, Object> map) {
		try {
			redisTemplate.opsForHash().putAll(key, map);
			return true;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return false;
		}
	}

TestRedis

测试类

package com.icomac;

import java.util.HashMap;
import java.util.Map;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * TestRedis
 * 
 * @author IComac
 * @date 2019-04-23
 */
public class TestRedis {
	
	public static void main(String[] args) throws Exception{
		
		ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
		
		RedisUtil redisUtil = (RedisUtil)context.getBean("redisUtil");
		
		//====================testString======================
		redisUtil.set("name", "icomac");
		System.out.println(redisUtil.get("name"));
		redisUtil.del("name");
		System.out.println(redisUtil.get("name"));
		
		//====================testNumber======================
		long incr = redisUtil.incr("number", 1);
		System.out.println(incr);
		incr = redisUtil.incr("number", 1);
		System.out.println(incr);
		
		//====================testMap=========================
		Map<String, Object> map = new HashMap<>();
		map.put("name", "meepo");
		map.put("pwd", "password");
		redisUtil.hmset("user", map);
		System.out.println(redisUtil.hget("user","name"));
		
	}
}

测试结果

redis客户端自动重连jedis redis连接多久会断开_Redis

 

在github上可以查看完整代码以及相关的引用包