spring+redis实现数据的缓存

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

1、实现目标

通过redis缓存数据。(目的不是加快查询的速度,而是减少数据库的负担)

2、所需jar包

注意:jdies和commons-pool两个jar的版本是有对应关系的,注意引入jar包是要配对使用,否则将会报错。因为commons-pooljar的目录根据版本的变化,目录结构会变。前面的版本是org.apache.pool,而后面的版本是org.apache.pool2...

style="background-color: #0098dd; color: white; font-size: 17px; font-weight: bold;"3、redis简介

redis是一个key-value存储系统。和Memcached类似,它支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)、zset(sorted set --有序集合)和hash(哈希类型)。这些数据类型都支持push/pop、add/remove及取交集并集和差集及更丰富的操作,而且这些操作都是原子性的。在此基础上,redis支持各种不同方式的排序。与memcached一样,为了保证效率,数据都是缓存在内存中。区别的是redis会周期性的把更新的数据写入磁盘或者把修改操作写入追加的记录文件,并且在此基础上实现了master-slave(主从)

4、编码实现

1)、配置的文件(PRoperties)

将那些经常要变化的参数配置成独立的propertis,方便以后的修改

redis.properties

redis.hostName=127.0.0.1

redis.port=6379

redis.timeout=15000

redis.usePool=true

redis.maxIdle=6

redis.minEvictableIdleTimeMillis=300000

redis.numTestsPerEvictionRun=3

redis.timeBetweenEvictionRunsMillis=60000

2)、spring-redis.xml

redis的相关参数配置设置。参数的值来自上面的properties文件

<beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"default-autowire="byName"><beanid="jedisPoolConfig"class="redis.clients.jedis.JedisPoolConfig"><!--<property name="maxIdle" value="6"></property>

<property name="minEvictableIdleTimeMillis" value="300000"></property>

<property name="numTestsPerEvictionRun" value="3"></property>

<property name="timeBetweenEvictionRunsMillis" value="60000"></property>--><propertyname="maxIdle"value="${redis.maxIdle}"></property><propertyname="minEvictableIdleTimeMillis"value="${redis.minEvictableIdleTimeMillis}"></property><propertyname="numTestsPerEvictionRun"value="${redis.numTestsPerEvictionRun}"></property><propertyname="timeBetweenEvictionRunsMillis"value="${redis.timeBetweenEvictionRunsMillis}"></property></bean><beanid="jedisConnectionFactory"class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"destroy-method="destroy"><propertyname="poolConfig"ref="jedisPoolConfig"></property><propertyname="hostName"value="${redis.hostName}"></property><propertyname="port"value="${redis.port}"></property><propertyname="timeout"value="${redis.timeout}"></property><propertyname="usePool"value="${redis.usePool}"></property></bean><beanid="jedisTemplate"class="org.springframework.data.redis.core.RedisTemplate"><propertyname="connectionFactory"ref="jedisConnectionFactory"></property><propertyname="keySerializer"><beanclass="org.springframework.data.redis.serializer.StringRedisSerializer"/></property><propertyname="valueSerializer"><beanclass="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/></property></bean></beans>

3)、applicationContext.xml

spring的总配置文件,在里面假如一下的代码

<beanclass="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><propertyname="systemPropertiesModeName"value="SYSTEM_PROPERTIES_MODE_OVERRIDE"/><propertyname="ignoreResourceNotFound"value="true"/><propertyname="locations"><list><value>classpath*:/META-INF/config/redis.properties</value></list></property></bean><importresource="spring-redis.xml"/>

4)、web。xml

设置spring的总配置文件在项目启动时加载

<context-param><param-name>contextConfigLocation</param-name><param-value>classpath*:/META-INF/applicationContext.xml</param-value><!----></context-param>

5)、redis缓存工具类

ValueOperations——基本数据类型和实体类的缓存

ListOperations ——list的缓存

SetOperations ——set的缓存

HashOperationsMap的缓存

importjava.io.Serializable;importjava.util.ArrayList;importjava.util.HashMap;importjava.util.HashSet;importjava.util.Iterator;importjava.util.List;importjava.util.Map;importjava.util.Set;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.beans.factory.annotation.Qualifier;importorg.springframework.context.support.ClassPathXmlApplicationContext;importorg.springframework.data.redis.core.BoundSetOperations;importorg.springframework.data.redis.core.HashOperations;importorg.springframework.data.redis.core.ListOperations;importorg.springframework.data.redis.core.RedisTemplate;importorg.springframework.data.redis.core.SetOperations;importorg.springframework.data.redis.core.ValueOperations;importorg.springframework.stereotype.Service;

@ServicepublicclassRedisCacheUtil<T>{

@Autowired @Qualifier("jedisTemplate")publicRedisTemplate redisTemplate;/*** 缓存基本的对象,Integer、String、实体类等

*@paramkey 缓存的键值

*@paramvalue 缓存的值

*@return缓存的对象*/public<T> ValueOperations<String,T>setCacheObject(String key,T value)

{

ValueOperations<String,T> operation =redisTemplate.opsForValue();

operation.set(key,value);returnoperation;

}/*** 获得缓存的基本对象。

*@paramkey 缓存键值

*@paramoperation

*@return缓存键值对应的数据*/public<T> T getCacheObject(String key/*,ValueOperations<String,T> operation*/)

{

ValueOperations<String,T> operation =redisTemplate.opsForValue();returnoperation.get(key);

}/*** 缓存List数据

*@paramkey 缓存的键值

*@paramdataList 待缓存的List数据

*@return缓存的对象*/public<T> ListOperations<String, T> setCacheList(String key,List<T>dataList)

{

ListOperations listOperation=redisTemplate.opsForList();if(null!=dataList)

{intsize =dataList.size();for(inti = 0; i < size ; i ++)

{

listOperation.rightPush(key,dataList.get(i));

}

}returnlistOperation;

}/*** 获得缓存的list对象

*@paramkey 缓存的键值

*@return缓存键值对应的数据*/public<T> List<T>getCacheList(String key)

{

List<T> dataList =newArrayList<T>();

ListOperations<String,T> listOperation =redisTemplate.opsForList();

Long size=listOperation.size(key);for(inti = 0 ; i < size ; i ++)

{

dataList.add((T) listOperation.leftPop(key));

}returndataList;

}/*** 缓存Set

*@paramkey 缓存键值

*@paramdataSet 缓存的数据

*@return缓存数据的对象*/public<T> BoundSetOperations<String,T> setCacheSet(String key,Set<T>dataSet)

{

BoundSetOperations<String,T> setOperation =redisTemplate.boundSetOps(key);/*T[] t = (T[]) dataSet.toArray();

setOperation.add(t);*/Iterator<T> it =dataSet.iterator();while(it.hasNext())

{

setOperation.add(it.next());

}returnsetOperation;

}/*** 获得缓存的set

*@paramkey

*@paramoperation

*@return*/publicSet<T> getCacheSet(String key/*,BoundSetOperations<String,T> operation*/)

{

Set<T> dataSet =newHashSet<T>();

BoundSetOperations<String,T> operation =redisTemplate.boundSetOps(key);

Long size=operation.size();for(inti = 0 ; i < size ; i++)

{

dataSet.add(operation.pop());

}returndataSet;

}/*** 缓存Map

*@paramkey

*@paramdataMap

*@return*/public<T> HashOperations<String,String,T> setCacheMap(String key,Map<String,T>dataMap)

{

HashOperations hashOperations=redisTemplate.opsForHash();if(null!=dataMap)

{for(Map.Entry<String, T>entry : dataMap.entrySet()) {/*System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());*/hashOperations.put(key,entry.getKey(),entry.getValue());

}

}returnhashOperations;

}/*** 获得缓存的Map

*@paramkey

*@paramhashOperation

*@return*/public<T> Map<String,T> getCacheMap(String key/*,HashOperations<String,String,T> hashOperation*/)

{

Map<String, T> map =redisTemplate.opsForHash().entries(key);/*Map<String, T> map = hashOperation.entries(key);*/returnmap;

}/*** 缓存Map

*@paramkey

*@paramdataMap

*@return*/public<T> HashOperations<String,Integer,T> setCacheIntegerMap(String key,Map<Integer,T>dataMap)

{

HashOperations hashOperations=redisTemplate.opsForHash();if(null!=dataMap)

{for(Map.Entry<Integer, T>entry : dataMap.entrySet()) {/*System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());*/hashOperations.put(key,entry.getKey(),entry.getValue());

}

}returnhashOperations;

}/*** 获得缓存的Map

*@paramkey

*@paramhashOperation

*@return*/public<T> Map<Integer,T> getCacheIntegerMap(String key/*,HashOperations<String,String,T> hashOperation*/)

{

Map<Integer, T> map =redisTemplate.opsForHash().entries(key);/*Map<String, T> map = hashOperation.entries(key);*/returnmap;

}

}

6)、测试

这里测试我是在项目启动的时候到数据库中查找出国家和城市的数据,进行缓存,之后将数据去出

6.1 项目启动时缓存数据

importjava.util.HashMap;importjava.util.List;importjava.util.Map;importorg.apache.log4j.Logger;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.context.ApplicationListener;importorg.springframework.context.event.ContextRefreshedEvent;importorg.springframework.stereotype.Service;importcom.test.model.City;importcom.test.model.Country;importcom.zcr.test.User;/** 监听器,用于项目启动的时候初始化信息*/@ServicepublicclassStartAddCacheListenerimplementsApplicationListener<ContextRefreshedEvent>{//日志privatefinalLogger log= Logger.getLogger(StartAddCacheListener.class);

@AutowiredprivateRedisCacheUtil<Object>redisCache;

@Autowiredprivate

BrandStoreService brandStoreService;

@OverridepublicvoidonApplicationEvent(ContextRefreshedEvent event)

{//spring 启动的时候缓存城市和国家等信息if(event.getApplicationContext().getDisplayName().equals("Root WebApplicationContext"))

{

System.out.println("\n\n\n_________\n\n缓存数据 \n\n ________\n\n\n\n");

List<City> cityList =

brandStoreService.selectAllCityMessage();

List<Country> countryList =

brandStoreService.selectAllCountryMessage();

Map<Integer,City> cityMap =newHashMap<Integer,City>();

Map<Integer,Country> countryMap =newHashMap<Integer, Country>();intcityListSize =cityList.size();intcountryListSize =countryList.size();for(inti = 0 ; i < cityListSize ; i ++)

{

cityMap.put(cityList.get(i).getCity_id(), cityList.get(i));

}for(inti = 0 ; i < countryListSize ; i ++)

{

countryMap.put(countryList.get(i).getCountry_id(), countryList.get(i));

}

redisCache.setCacheIntegerMap("cityMap", cityMap);

redisCache.setCacheIntegerMap("countryMap", countryMap);

}

}

}

6.2 获取缓存数据

@AutowiredprivateRedisCacheUtil<User>redisCache;

@RequestMapping("testGetCache")publicvoidtestGetCache()

{/*Map<String,Country> countryMap = redisCacheUtil1.getCacheMap("country");

Map<String,City> cityMap = redisCacheUtil.getCacheMap("city");*/Map<Integer,Country> countryMap = redisCacheUtil1.getCacheIntegerMap("countryMap");

Map<Integer,City> cityMap = redisCacheUtil.getCacheIntegerMap("cityMap");for(intkey : countryMap.keySet())

{

System.out.println("key = " + key + ",value=" +countryMap.get(key));

}

System.out.println("------------city");for(intkey : cityMap.keySet())

{

System.out.println("key = " + key + ",value=" +cityMap.get(key));

}

}

由于Spring在配置文件中配置的bean默认是单例的,所以只需要通过Autowired注入,即可得到原先的缓存类。

致谢:感谢您的阅读!

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航