spring + redis 实现数据的缓存

1、实现目标

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

2、所需jar包

  

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

style=" 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. Spring通过AOP实现对Redis的缓存同步

    废话不多说 说下思路:使用aop注解,在Service实现类添加需要用到redis的方法上,当每次请求过来则对其进行拦截,如果是查询则从redis进行get key,如果是update则删除key,防 ...

  2. Spring Boot 整合 Redis 实现缓存操作

    摘要: 原创出处 www.bysocket.com 「泥瓦匠BYSocket 」欢迎转载,保留摘要,谢谢!   『 产品没有价值,开发团队再优秀也无济于事 – <启示录> 』   本文提纲 ...

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

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

  4. SpringBoot集成Redis实现缓存处理(Spring AOP实现)

    第一章 需求分析 计划在Team的开源项目里加入Redis实现缓存处理,因为业务功能已经实现了一部分,通过写Redis工具类,然后引用,改动量较大,而且不可以实现解耦合,所以想到了Spring框架的A ...

  5. spring使用redis做缓存

    缓存 什么是缓存? 在高并发下,为了提高访问的性能,需要将数据库中 一些经常展现和不会频繁变更的数据,存放在存取速率更快的内存中.这样可以 降低数据的获取时间,带来更好的体验 减轻数据库的压力 缓存适 ...

  6. Spring Boot + Mybatis + Redis二级缓存开发指南

    Spring Boot + Mybatis + Redis二级缓存开发指南 背景 Spring-Boot因其提供了各种开箱即用的插件,使得它成为了当今最为主流的Java Web开发框架之一.Mybat ...

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

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

  8. 【原】Spring AOP实现对Redis的缓存同步

    前言:刚开始采用spring cache作为缓存数据,到后面发现扩展性不灵活,于是基于sprig cache原理自定义一套规则用于缓存数据. 请求过程: 根据请求参数生成Key,后面我们会对生成Key ...

  9. spring配置redis注解缓存

    前几天在spring整合Redis的时候使用了手动的方式,也就是可以手动的向redis添加缓存与清除缓存,参考:http://www.cnblogs.com/qlqwjy/p/8562703.html ...

随机推荐

  1. rapidminer 数据导入及几个算子简单应用

    rapidminer 数据导入及几个算子简单应用 一. 数据集选择 本次实验选择的数据集为: bank-data.csv 其中有600条数据 结构如下图: 二.数据集文件格式转换 Rapidminer ...

  2. c#省市联动

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...

  3. 类型解释器——C专家编程读书笔记

    对于声明,应该按下面的步骤来进行解释: 1) 声明从它的名字开始读取,然后按照优先级顺序依次读取 2) 优先级顺序 a) 括号括起来的部分 b) 后缀操作符,()表示函数,[]表示数组 c) 前缀操作 ...

  4. 20150601_Andriod 打开新窗体

    <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="htt ...

  5. Cow Bowling

    Cow Bowling Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 15585 Accepted: 10363 Descrip ...

  6. Sudoku

    Sudoku Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 15952 Accepted: 7791 Special Judge ...

  7. PowerShell处理RSS信息

    转载请注明出自天外归云的博客园:http://www.cnblogs.com/LanTianYou/ 环境:Windows Server 2012 EN(解决PowerShell控制台中文乱码问题:方 ...

  8. AIM Tech Round 3 (Div. 2) B

    Description Vasya takes part in the orienteering competition. There are n checkpoints located along ...

  9. c++类中的常量

    C++类中的常量 由于#define 定义的宏常量是全局的,不能达到目的,于是想当然地觉得应该用 const 修饰数据成员来实现.const 数据成员的确是存在的,但其含义却不是我们所期望的.cons ...

  10. sql去除某个字段中的某个字符串 replace

    update A set col1 =REPLACE ( col1 ,'测试' , '') where col1 like '%测试%' 在使用过程中如果遇到text类型的字段时会报 参数数据类型 t ...