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(主从)
3、编码实现
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文件
3)、applicationContext.xml
spring的总配置文件,在里面假如一下的代码
classpath*:/meta-INF/config/redis.properties
4)、web.xml
设置spring的总配置文件在项目启动时加载
contextConfigLocation classpath*:/meta-INF/applicationContext.xml
5)、redis缓存工具类
ValueOperations ——基本数据类型和实体类的缓存
ListOperations ——list的缓存
SetOperations ——set的缓存
HashOperations Map的缓存
import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.data.redis.core.BoundSetOperations; import org.springframework.data.redis.core.HashOperations; import org.springframework.data.redis.core.ListOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.SetOperations; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Service; @Service public class RedisCacheUtil{ @Autowired @Qualifier("jedisTemplate") public RedisTemplate redisTemplate; public ValueOperations setCacheObject(String key,T value) { ValueOperations operation = redisTemplate.opsForValue(); operation.set(key,value); return operation; } public T getCacheObject(String key) { ValueOperations operation = redisTemplate.opsForValue(); return operation.get(key); } public ListOperations setCacheList(String key,List dataList) { ListOperations listOperation = redisTemplate.opsForList(); if(null != dataList) { int size = dataList.size(); for(int i = 0; i < size ; i ++) { listOperation.rightPush(key,dataList.get(i)); } } return listOperation; } public List getCacheList(String key) { List dataList = new ArrayList (); ListOperations listOperation = redisTemplate.opsForList(); Long size = listOperation.size(key); for(int i = 0 ; i < size ; i ++) { dataList.add((T) listOperation.leftPop(key)); } return dataList; } public BoundSetOperations setCacheSet(String key,Set dataSet) { BoundSetOperations setOperation = redisTemplate.boundSetOps(key); Iterator it = dataSet.iterator(); while(it.hasNext()) { setOperation.add(it.next()); } return setOperation; } public Set getCacheSet(String key) { Set dataSet = new HashSet (); BoundSetOperations operation = redisTemplate.boundSetOps(key); Long size = operation.size(); for(int i = 0 ; i < size ; i++) { dataSet.add(operation.pop()); } return dataSet; } public HashOperations setCacheMap(String key,Map dataMap) { HashOperations hashOperations = redisTemplate.opsForHash(); if(null != dataMap) { for (Map.Entry entry : dataMap.entrySet()) { hashOperations.put(key,entry.getKey(),entry.getValue()); } } return hashOperations; } public Map getCacheMap(String key) { Map map = redisTemplate.opsForHash().entries(key); return map; } public HashOperations setCacheIntegerMap(String key,Map dataMap) { HashOperations hashOperations = redisTemplate.opsForHash(); if(null != dataMap) { for (Map.Entry entry : dataMap.entrySet()) { hashOperations.put(key,entry.getKey(),entry.getValue()); } } return hashOperations; } public Map getCacheIntegerMap(String key) { Map map = redisTemplate.opsForHash().entries(key); return map; } }
6)、测试
这里测试我是在项目启动的时候到数据库中查找出国家和城市的数据,进行缓存,之后将数据去除。
6.1 项目启动时缓存数据
import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Service; import com.test.model.City; import com.test.model.Country; import com.zcr.test.User; @Service public class StartAddCacheListener implements ApplicationListener{ //日志 private final Logger log= Logger.getLogger(StartAddCacheListener.class); @Autowired private RedisCacheUtil
6.2 获取缓存数据
@Autowired private RedisCacheUtilredisCache; @RequestMapping("testGetCache") public void testGetCache() { Map countryMap = redisCacheUtil1.getCacheIntegerMap("countryMap"); Map cityMap = redisCacheUtil.getCacheIntegerMap("cityMap"); for(int key : countryMap.keySet()) { System.out.println("key = " + key + ",value=" + countryMap.get(key)); } System.out.println("------------city"); for(int key : cityMap.keySet()) { System.out.println("key = " + key + ",value=" + cityMap.get(key)); } }
由于Spring在配置文件中配置的bean默认是单例的,所以只需要通过Autowired注入,即可得到原先的缓存类。
以上就是spring+redis实现数据缓存的方法,希望对大家的学习有所帮助。



