欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

spring结合redis如何实现数据的缓存

程序员文章站 2024-03-07 13:04:27
1、实现目标   通过redis缓存数据。(目的不是加快查询的速度,而是减少数据库的负担)   2、所需jar包     注意:jdies和commons-pool...

1、实现目标

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

2、所需jar包

 spring结合redis如何实现数据的缓存

  注意: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文件

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