在SSM项目中使用redis实现数据缓存

redis是一个key-value存储系统。和Memcached类似,它支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)、zset(sorted set --有序集合)和hash(哈希类型)。

redis的具体操作不详述,介绍一下redis在SSM项目中的使用

一、redis.properties配置文件

redis.hostname=127.0.0.1
redis.port=6379
redis.database=0
redis.pool.maxActive=600
redis.pool.maxIdle=300
redis.pool.maxWait=3000
redis.pool.testOnBorrow=true

二、spring文件加载redis.properties

<context:property-placeholder location="classpath:redis.properties" />

三、redis连接池配置spring-redis.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd">
	
	<!-- Redis连接池的设置 -->
	<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
		<!-- 控制一个pool可分配多少个jedis实例 -->
		<property name="maxTotal" value="${redis.pool.maxActive}" />
		<!-- 连接池中最多可空闲maxIdle个连接,这里取值为20,表示即使没有数据库连接是依旧保持20空闲的连接 -->
		<property name="maxIdle" value="${redis.pool.maxIdle}" />
		<!-- 最大等待时间:当没有可用连接时,连接池等待连接被归还的最大时间(以毫秒计算),超过时间则抛出异常 -->
		<property name="maxWaitMillis" value="${redis.pool.maxWait}" />
		<!-- 在获取连接的时候检查有效性 -->
		<property name="testOnBorrow" value="${redis.pool.testOnBorrow}" />
	</bean>
	<!-- 创建Redis连接池,并做相关配置 -->
	<bean id="jedisWritePool" class="top.maniy.common.cache.JedisPoolWriper"
		depends-on="jedisPoolConfig">
		<constructor-arg index="0" ref="jedisPoolConfig" />
		<constructor-arg index="1" value="${redis.hostname}" />
		<constructor-arg index="2" value="${redis.port}" type="int" />
	</bean>
	<bean id="jedisKeys" class="top.maniy.common.cache.JedisUtil$Keys"
		scope="singleton">	
	</bean>
	<bean id="jedisStrings" class="top.maniy.common.cache.JedisUtil$Strings"
		scope="singleton">
	</bean>
	<bean id="jedisLists" class="top.maniy.common.cache.JedisUtil$Lists"
		scope="singleton">
	</bean>
	<bean id="jedisSets" class="top.maniy.common.cache.JedisUtil$Sets"
		scope="singleton">
	</bean>
	<bean id="jedisHash" class="top.maniy.common.cache.JedisUtil$Hash"
		scope="singleton">	
	</bean>
	<bean id="jedisUtil" class="top.maniy.common.cache.JedisUtil"
		scope="singleton">
		<property name="jedisPool">
			<ref bean="jedisWritePool" />
		</property>
	</bean>
</beans>    

四、JedisPoolWriper

import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * 强指定redis的JedisPool接口构造函数,这样才能在centos成功创建jedispool
 * 
 * @author xiangze
 *
 */
public class JedisPoolWriper {
	private JedisPool jedisPool;

	public JedisPoolWriper(final JedisPoolConfig poolConfig, final String host,
			final int port) {
		try {
			jedisPool = new JedisPool(poolConfig, host, port);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public JedisPool getJedisPool() {
		return jedisPool;
	}

	public void setJedisPool(JedisPool jedisPool) {
		this.jedisPool = jedisPool;
	}

}

五、jedis工具栏JedisUtil

public class JedisUtil {
	/**
	 * 缓存生存时间
	 */
	private final int expire = 60000;
	/** 操作Key的方法 */
	public Keys KEYS;
	private JedisPool jedisPool;

	public JedisPool getJedisPool() {
		return jedisPool;
	}

	public void setJedisPool(JedisPoolWriper jedisPoolWriper) {
		this.jedisPool = jedisPoolWriper.getJedisPool();
	}

	public JedisPool getPool() {
		return jedisPool;
	}

	/**
	 * 从jedis连接池中获取获取jedis对象
	 * 
	 * @return
	 */
	public Jedis getJedis() {
		return jedisPool.getResource();
	}

	// *******************************************Keys*******************************************//
	public class Keys {

	
		/**
		 * 更改key
		 * 
		 * @param String
		 *            oldkey
		 * @param String
		 *            newkey
		 * @return 状态码
		 * */
		public String rename(String oldkey, String newkey) {
			return rename(SafeEncoder.encode(oldkey),
					SafeEncoder.encode(newkey));
		}

		/**
		 * 更改key,仅当新key不存在时才执行
		 * 
		 * @param String
		 *            oldkey
		 * @param String
		 *            newkey
		 * @return 状态码
		 * */
		public long renamenx(String oldkey, String newkey) {
			Jedis jedis = getJedis();
			long status = jedis.renamenx(oldkey, newkey);
			jedis.close();
			return status;
		}

		/**
		 * 更改key
		 * 
		 * @param String
		 *            oldkey
		 * @param String
		 *            newkey
		 * @return 状态码
		 * */
		public String rename(byte[] oldkey, byte[] newkey) {
			Jedis jedis = getJedis();
			String status = jedis.rename(oldkey, newkey);
			jedis.close();
			return status;
		}

		/**
		 * 设置key的过期时间,以秒为单位
		 * 
		 * @param String
		 *            key
		 * @param 时间
		 *            ,已秒为单位
		 * @return 影响的记录数
		 * */
		public long expired(String key, int seconds) {
			Jedis jedis = getJedis();
			long count = jedis.expire(key, seconds);
			jedis.close();
			return count;
		}
		/**
		 * 判断key是否存在
		 * 
		 * @param String
		 *            key
		 * @return boolean
		 * */
		public boolean exists(String key) {
			// ShardedJedis sjedis = getShardedJedis();
			Jedis sjedis = getJedis();
			boolean exis = sjedis.exists(key);
			sjedis.close();
			return exis;
		}

service层操作插入缓存

@Service
@Transactional
public class BaseDictServiceImpl implements BaseDictService {

	@Autowired
	private BaseDictMapper baseDictMapper;
	
	@Autowired
	private JedisUtil.Keys jedisKeys;
	
	@Autowired
	private JedisUtil.Strings jedisStrings;
	
	private static String DICTLISTKEY ="dictlist";//多个传入不同的code方法   key会相同,后面的value覆盖前面的redis里value
	
	public List<BaseDict> selectBaseDictListByCode(String code){
		String key = DICTLISTKEY;
		List<BaseDict> dictList =null;
		ObjectMapper mapper=new ObjectMapper();
		if(!jedisKeys.exists(key)) {
			dictList = baseDictMapper.selectBaseDictListByCode(code);
			String jsonString = null;
			try {
				jsonString =mapper.writeValueAsString(dictList);
			} catch (JsonProcessingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			
			}
			jedisStrings.set(key, jsonString);
		}else {
			String jsonString = jedisStrings.get(key);
			JavaType javaType=mapper.getTypeFactory().constructParametricType(ArrayList.class, BaseDict.class);
			try {
				dictList = mapper.readValue(jsonString, javaType);
			} catch (JsonParseException e) {
				e.printStackTrace();
			} catch (JsonMappingException e) {
		
				e.printStackTrace();
			} catch (IOException e) {

				e.printStackTrace();
			}
		}
		return dictList;
	}
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值