全网整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:400-708-3566

详解redis与spring的整合(使用缓存)

1、实现目标

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

2、所需jar包

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

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

<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实现数据缓存的方法,希望对大家的学习有所帮助。也希望大家多多支持。


# spring  # redis缓存  # 整合redis  # spring整合redis缓存  # SpringBoot 开启Redis缓存及使用方法  # 浅谈SpringCache与redis集成实现缓存解决方案  # spring整合redis实现数据缓存的实例代码  # spring整合redisson开启缓存方式  # 键值  # 都是  # 配置文件  # 在此基础上  # 启动时  # 的是  # 是一个  # 是在  # 是有  # 将会  # 所需  # 实体类  # 只需要  # 在里面  # 后将  # 报错  # 数据库中  # 大家多多  # 实现了  # 加载 


相关文章: 如何选择服务器才能高效搭建专属网站?  深圳企业网站制作设计,在深圳如何网上全流程注册公司?  江苏网站制作公司有哪些,江苏书法考级官方网站?  高端云建站费用究竟需要多少预算?  图册素材网站设计制作软件,图册的导出方式有几种?  c# 在ASP.NET Core中管理和取消后台任务  如何安全更换建站之星模板并保留数据?  如何高效生成建站之星成品网站源码?  武汉网站如何制作,黄黄高铁武穴北站途经哪些村庄?  七夕网站制作视频,七夕大促活动怎么报名?  如何在Tomcat中配置并部署网站项目?  建站主机如何选?性能与价格怎样平衡?  网页设计网站制作软件,microsoft office哪个可以创建网页?  自助网站制作软件,个人如何自助建网站?  合肥制作网站的公司有哪些,合肥聚美网络科技有限公司介绍?  常州企业建站如何选择最佳模板?  建站168自助建站系统:快速模板定制与SEO优化指南  如何通过虚拟主机快速完成网站搭建?  深入理解Android中的xmlns:tools属性  建站之星多图banner生成与模板自定义指南  深圳网站制作费用多少钱,读秀,深圳文献港这样的网站很多只提供网上试读,但有些人只要提供试读的文章就能全篇下载,这个是怎么弄的?  如何在云主机上快速搭建网站?  高端智能建站公司优选:品牌定制与SEO优化一站式服务  详解免费开源的.NET多类型文件解压缩组件SharpZipLib(.NET组件介绍之七)  如何制作算命网站,怎么注册算命网站?  如何在阿里云服务器自主搭建网站?  香港服务器网站卡顿?如何解决网络延迟与负载问题?  ,柠檬视频怎样兑换vip?  可靠的网站设计制作软件,做网站设计需要什么样的电脑配置?  如何批量查询域名的建站时间记录?  正规网站制作公司有哪些,目前国内哪家网页网站制作设计公司比较专业靠谱?口碑好?  创业网站制作流程,创业网站可靠吗?  南阳网站制作公司推荐,小学电子版试卷去哪里找资源好?  上海网站制作开发公司,上海买房比较好的网站有哪些?  c# F# 的 MailboxProcessor 和 C# 的 Actor 模型  建站主机选购指南与交易推荐:核心配置解析  如何自己制作一个网站链接,如何制作一个企业网站,建设网站的基本步骤有哪些?  如何使用Golang table-driven基准测试_多组数据测量函数效率  高防服务器租用首荐平台,企业级优惠套餐快速部署  建站之星代理费用多少?最新价格详情介绍  制作旅游网站html,怎样注册旅游网站?  广州营销型建站服务商推荐:技术优势与SEO优化解析  python的本地网站制作,如何创建本地站点?  如何基于云服务器快速搭建网站及云盘系统?  如何在阿里云通过域名搭建网站?  c++怎么使用类型萃取type_traits_c++ 模板元编程类型判断【方法】  香港网站服务器数量如何影响SEO优化效果?  如何在云主机快速搭建网站站点?  如何快速搭建高效可靠的建站解决方案?  深圳网站制作平台,深圳市做网站好的公司有哪些? 

您的项目需求

*请认真填写需求信息,我们会在24小时内与您取得联系。