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文件

<beans xmlns="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">
<bean id="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> --> <property name="maxIdle" value="${redis.maxIdle}"></property>
<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.hostName}"></property>
<property name="port" value="${redis.port}"></property>
<property name="timeout" value="${redis.timeout}"></property>
<property name="usePool" value="${redis.usePool}"></property>
</bean>
<bean id="jedisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory"></property>
<property name="keySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
<property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
</property>
</bean>
</beans>

3)、applicationContext.xml

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

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="ignoreResourceNotFound" value="true" />
<property name="locations">
<list> <value>classpath*:/META-INF/config/redis.properties</value>
</list>
</property>
</bean> <import resource="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的缓存

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<T>
{ @Autowired @Qualifier("jedisTemplate")
public RedisTemplate redisTemplate; /**
* 缓存基本的对象,Integer、String、实体类等
* @param key 缓存的键值
* @param value 缓存的值
* @return 缓存的对象
*/
public <T> ValueOperations<String,T> setCacheObject(String key,T value)
{ ValueOperations<String,T> operation = redisTemplate.opsForValue();
operation.set(key,value);
return operation;
} /**
* 获得缓存的基本对象。
* @param key 缓存键值
* @param operation
* @return 缓存键值对应的数据
*/
public <T> T getCacheObject(String key/*,ValueOperations<String,T> operation*/)
{
ValueOperations<String,T> operation = redisTemplate.opsForValue();
return operation.get(key);
} /**
* 缓存List数据
* @param key 缓存的键值
* @param dataList 待缓存的List数据
* @return 缓存的对象
*/
public <T> ListOperations<String, T> setCacheList(String key,List<T> 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;
} /**
* 获得缓存的list对象
* @param key 缓存的键值
* @return 缓存键值对应的数据
*/
public <T> List<T> getCacheList(String key)
{
List<T> dataList = new ArrayList<T>();
ListOperations<String,T> listOperation = redisTemplate.opsForList();
Long size = listOperation.size(key); for(int i = 0 ; i < size ; i ++)
{
dataList.add((T) listOperation.leftPop(key));
} return dataList;
} /**
* 缓存Set
* @param key 缓存键值
* @param dataSet 缓存的数据
* @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());
} return setOperation;
} /**
* 获得缓存的set
* @param key
* @param operation
* @return
*/
public Set<T> getCacheSet(String key/*,BoundSetOperations<String,T> operation*/)
{
Set<T> dataSet = new HashSet<T>();
BoundSetOperations<String,T> operation = redisTemplate.boundSetOps(key); Long size = operation.size();
for(int i = 0 ; i < size ; i++)
{
dataSet.add(operation.pop());
}
return dataSet;
} /**
* 缓存Map
* @param key
* @param dataMap
* @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());
} } return hashOperations;
} /**
* 获得缓存的Map
* @param key
* @param hashOperation
* @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);*/
return map;
} /**
* 缓存Map
* @param key
* @param dataMap
* @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());
} } return hashOperations;
} /**
* 获得缓存的Map
* @param key
* @param hashOperation
* @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);*/
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<ContextRefreshedEvent>
{
//日志
private final Logger log= Logger.getLogger(StartAddCacheListener.class); @Autowired
private RedisCacheUtil<Object> redisCache; @Autowired
private BrandStoreService brandStoreService; @Override
public void onApplicationEvent(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 = new HashMap<Integer,City>(); Map<Integer,Country> countryMap = new HashMap<Integer, Country>(); int cityListSize = cityList.size();
int countryListSize = countryList.size(); for(int i = 0 ; i < cityListSize ; i ++ )
{
cityMap.put(cityList.get(i).getCity_id(), cityList.get(i));
} for(int i = 0 ; i < countryListSize ; i ++ )
{
countryMap.put(countryList.get(i).getCountry_id(), countryList.get(i));
} redisCache.setCacheIntegerMap("cityMap", cityMap);
redisCache.setCacheIntegerMap("countryMap", countryMap);
}
} }

6.2  获取缓存数据

    @Autowired
private RedisCacheUtil<User> redisCache; @RequestMapping("testGetCache")
public void testGetCache()
{
/*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(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 实现数据的缓存的更多相关文章

  1. ServletContextListener 启动SPRING加载数据到缓存的应用

    java 代码 public class LoadTreeForXML implements ServletContextListener {    public void contextInitia ...

  2. 深入理解Spring Redis的使用 (八)、Spring Redis实现 注解 自动缓存

    项目中有些业务方法希望在有缓存的时候直接从缓存获取,不再执行方法,来提高吞吐率.而且这种情况有很多.如果为每一个方法都写一段if else的代码,导致耦合非常大,不方便后期的修改. 思来想去,决定使用 ...

  3. spring+redis实现缓存

    spring + redis 实现数据的缓存 1.实现目标 通过redis缓存数据.(目的不是加快查询的速度,而是减少数据库的负担) 2.所需jar包 注意:jdies和commons-pool两个j ...

  4. Spring Boot使用redis做数据缓存

    1 添加redis支持 在pom.xml中添加 <dependency> <groupId>org.springframework.boot</groupId> & ...

  5. 学习Spring Boot:(二十五)使用 Redis 实现数据缓存

    前言 由于 Ehcache 存在于单个 java 程序的进程中,无法满足多个程序分布式的情况,需要将多个服务器的缓存集中起来进行管理,需要一个缓存的寄存器,这里使用的是 Redis. 正文 当应用程序 ...

  6. SpringBoot 结合 Spring Cache 操作 Redis 实现数据缓存

    系统环境: Redis 版本:5.0.7 SpringBoot 版本:2.2.2.RELEASE 参考地址: Redus 官方网址:https://redis.io/ 博文示例项目 Github 地址 ...

  7. 组件-------(一)redis系列--安装部署redis+实现redis分布式缓存 java+Spring+redis

    目的:解决单机session不能共享问题,插入查询数据库时间效率问题,实现分布式缓存. 准备材料:Redis 下载链接 http://pan.baidu.com/s/1dEGTxvV 相关jar包如果 ...

  8. 分布式缓存技术redis学习—— 深入理解Spring Redis的使用

    关于spring redis框架的使用,网上的例子很多很多.但是在自己最近一段时间的使用中,发现这些教程都是入门教程,包括很多的使用方法,与spring redis丰富的api大相径庭,真是浪费了这么 ...

  9. spring+redis的集成,redis做缓存

    1.前言 Redis是一个开源的使用ANSI C语言编写.支持网络.可基于内存亦可持久化的日志型.Key-Value数据库,并提供多种语言的API.我们都知道,在日常的应用中,数据库瓶颈是最容易出现的 ...

随机推荐

  1. 手机端Swiper 触屏滑动

    在线实例 默认 响应式 垂直 空间间隔 滚动 自动滚动 中心化 中心化自动 免费模式 多个滚动 水平滚动 grab-cursor 使用方法 <div class="swiper-con ...

  2. 【javascript激增的思考04】MVC与Backbone.js(beta)

    前言 最近整理了很多前端面试题的东西,今天又去参加了一次面试,不知各位烦不烦,我反正有点累了,于是我们今天继续回到我们前段时间研究的问题,我们再来看看MVC吧. 什么是MVC 又回到这个问题了,到底什 ...

  3. 微信 小程序 drawImage wx.canvasToTempFilePath wx.saveFile 获取设备宽高 尺寸问题

    以下问题测试环境为微信开发者0.10.102800,手机端iphone6,如有不对敬谢指出. 根据我的测试,context.drawImage,在开发者工具中并不能画出来,只有预览到手机中显示. wx ...

  4. gif动图快速制作方法(附工具)

    现在写博客或是wiki的过程中,会经常引用到图片,特别是客户端经常与页面相关所以截图不可避.但是越来越多的效果仅仅一张图片是无法清楚的描述.并且博客或是wiki也是支持gif图的.gif图的制作方法有 ...

  5. sqlite之WAL模式

    链接 概述 在3.7.0以后,WAL(Write-Ahead Log)模式可以使用,是另一种实现事务原子性的方法. WAL的优点 在大多数情况下更快 并行性更高.因为读操作和写操作可以并行. 文件IO ...

  6. html 出现的错误

    1.HTML页面为什么设置了UTF-8仍然中文乱码 用记事本写,保存后在网页上运行出现了乱码,换成GB2312能正确显示中文 代码没有问题,问题就出记事本身上. <meta charste=&q ...

  7. 【C语言】C语言运算符

    目录: [算术运算符] [自增运算符] [自减运算符] [关系运算符] [逻辑运算符] [三目运算符] [sizeof运算符] · 作用 1.算术运算符 +(加).-(减).*(乘)./(除).%(取 ...

  8. iOS 图片加载导致内存警告

    虽然UITableView和UICollectionView都有cell复用机制,但是如果利用SDWebImage加载的图片本身过大且cell复用池中的个数比较多(cell的Size越小,复用池中的c ...

  9. 手机影音1--SplashActivity

    /** * 1.设置被启动的Activity为单例模式 */ public class SplashActivity extends Activity { /** * 是否已经启动主页面 */ pri ...

  10. 在eclipse中把之前的Tomcat 6删掉,不能再建

    在eclipse中把之前的Tomcat 6删掉,重新配置一个,不料没有下一步. 解决的方法了,如下: 1.退出 eclipse 2.到[工程目录下]/.metadata/.plugins/org.ec ...