最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

spring結(jié)合redis如何實(shí)現(xiàn)數(shù)據(jù)的緩存

 更新時(shí)間:2015年12月01日 15:53:08   作者:WhyWin  
這篇文章主要介紹了spring結(jié)合redis如何實(shí)現(xiàn)數(shù)據(jù)的緩存,實(shí)現(xiàn)的目的目的不是加快查詢的速度,而是減少數(shù)據(jù)庫(kù)的負(fù)擔(dān),需要的朋友可以參考下

1、實(shí)現(xiàn)目標(biāo)

  通過(guò)redis緩存數(shù)據(jù)。(目的不是加快查詢的速度,而是減少數(shù)據(jù)庫(kù)的負(fù)擔(dān))  

2、所需jar包

 

  注意:jdies和commons-pool兩個(gè)jar的版本是有對(duì)應(yīng)關(guān)系的,注意引入jar包是要配對(duì)使用,否則將會(huì)報(bào)錯(cuò)。因?yàn)閏ommons-pooljar的目錄根據(jù)版本的變化,目錄結(jié)構(gòu)會(huì)變。前面的版本是org.apache.pool,而后面的版本是org.apache.pool2...

style="background-color: #0098dd; color: white; font-size: 17px; font-weight: bold;"3、redis簡(jiǎn)介

  redis是一個(gè)key-value存儲(chǔ)系統(tǒng)。和Memcached類似,它支持存儲(chǔ)的value類型相對(duì)更多,包括string(字符串)、list(鏈表)、set(集合)、zset(sorted set --有序集合)和hash(哈希類型)。這些數(shù)據(jù)類型都支持push/pop、add/remove及取交集并集和差集及更豐富的操作,而且這些操作都是原子性的。在此基礎(chǔ)上,redis支持各種不同方式的排序。與memcached一樣,為了保證效率,數(shù)據(jù)都是緩存在內(nèi)存中。區(qū)別的是redis會(huì)周期性的把更新的數(shù)據(jù)寫入磁盤或者把修改操作寫入追加的記錄文件,并且在此基礎(chǔ)上實(shí)現(xiàn)了master-slave(主從)

3、編碼實(shí)現(xiàn)

1)、配置的文件(properties)

  將那些經(jīng)常要變化的參數(shù)配置成獨(dú)立的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的相關(guān)參數(shù)配置設(shè)置。參數(shù)的值來(lái)自上面的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

  設(shè)置spring的總配置文件在項(xiàng)目啟動(dòng)時(shí)加載

 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath*:/META-INF/applicationContext.xml</param-value><!-- -->
 </context-param>

5)、redis緩存工具類

ValueOperations  ——基本數(shù)據(jù)類型和實(shí)體類的緩存
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;
 

 
 /**
  * 緩存基本的對(duì)象,Integer、String、實(shí)體類等
  * @param key 緩存的鍵值
  * @param value 緩存的值
  * @return  緩存的對(duì)象
  */
 public <T> ValueOperations<String,T> setCacheObject(String key,T value)
 {
  
  ValueOperations<String,T> operation = redisTemplate.opsForValue(); 
  operation.set(key,value);
  return operation;
 }
 
 /**
  * 獲得緩存的基本對(duì)象。
  * @param key  緩存鍵值
  * @param operation
  * @return   緩存鍵值對(duì)應(yīng)的數(shù)據(jù)
  */
 public <T> T getCacheObject(String key/*,ValueOperations<String,T> operation*/)
 {
  ValueOperations<String,T> operation = redisTemplate.opsForValue(); 
  return operation.get(key);
 }
 
 /**
  * 緩存List數(shù)據(jù)
  * @param key  緩存的鍵值
  * @param dataList 待緩存的List數(shù)據(jù)
  * @return   緩存的對(duì)象
  */
 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對(duì)象
  * @param key 緩存的鍵值
  * @return  緩存鍵值對(duì)應(yīng)的數(shù)據(jù)
  */
 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 緩存的數(shù)據(jù)
  * @return   緩存數(shù)據(jù)的對(duì)象
  */
 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)、測(cè)試

  這里測(cè)試我是在項(xiàng)目啟動(dòng)的時(shí)候到數(shù)據(jù)庫(kù)中查找出國(guó)家和城市的數(shù)據(jù),進(jìn)行緩存,之后將數(shù)據(jù)去除。

6.1  項(xiàng)目啟動(dòng)時(shí)緩存數(shù)據(jù)

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;

/*
 * 監(jiān)聽(tīng)器,用于項(xiàng)目啟動(dòng)的時(shí)候初始化信息
 */
@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 啟動(dòng)的時(shí)候緩存城市和國(guó)家等信息
  if(event.getApplicationContext().getDisplayName().equals("Root WebApplicationContext"))
  {
   System.out.println("\n\n\n_________\n\n緩存數(shù)據(jù) \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  獲取緩存數(shù)據(jù)

 @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默認(rèn)是單例的,所以只需要通過(guò)Autowired注入,即可得到原先的緩存類。

以上就是spring+redis實(shí)現(xiàn)數(shù)據(jù)緩存的方法,希望對(duì)大家的學(xué)習(xí)有所幫助。

相關(guān)文章

  • Java源碼解析之可重入鎖ReentrantLock

    Java源碼解析之可重入鎖ReentrantLock

    今天小編就為大家分享一篇關(guān)于Java源碼解析之可重入鎖ReentrantLock,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧
    2019-01-01
  • Spring AOP注解案例及基本原理詳解

    Spring AOP注解案例及基本原理詳解

    這篇文章主要介紹了Spring AOP注解案例及基本原理詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-06-06
  • Java面試題-實(shí)現(xiàn)復(fù)雜鏈表的復(fù)制代碼分享

    Java面試題-實(shí)現(xiàn)復(fù)雜鏈表的復(fù)制代碼分享

    這篇文章主要介紹了Java面試題-實(shí)現(xiàn)復(fù)雜鏈表的復(fù)制代碼分享,小編覺(jué)得還是挺不錯(cuò)的,具有參考價(jià)值,需要的朋友可以了解下。
    2017-10-10
  • maven工程如何讀取resource目錄下配置文件

    maven工程如何讀取resource目錄下配置文件

    這篇文章主要介紹了maven工程如何讀取,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-11-11
  • IDEA設(shè)置字體隨鼠標(biāo)滾動(dòng)放大縮小的實(shí)現(xiàn)

    IDEA設(shè)置字體隨鼠標(biāo)滾動(dòng)放大縮小的實(shí)現(xiàn)

    這篇文章主要介紹了IDEA設(shè)置字體隨鼠標(biāo)滾動(dòng)放大縮小的實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-01-01
  • Springboot中的@Conditional注解詳解

    Springboot中的@Conditional注解詳解

    這篇文章主要介紹了Springboot中的@Conditional注解詳解,@Conditional來(lái)源于spring-context包下的一個(gè)注解,Conditional中文是條件的意思,@Conditional注解它的作用是按照一定的條件進(jìn)行判斷,滿足條件給容器注冊(cè)bean,需要的朋友可以參考下
    2023-09-09
  • SpringBoot多環(huán)境配置及日志記錄器詳解

    SpringBoot多環(huán)境配置及日志記錄器詳解

    這篇文章主要介紹了SpringBoot多環(huán)境配置及日志記錄器詳解,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧
    2024-01-01
  • SpringBoot集成Kafka 配置工具類的詳細(xì)代碼

    SpringBoot集成Kafka 配置工具類的詳細(xì)代碼

    spring-kafka 是基于 java版的 kafka client與spring的集成,提供了 KafkaTemplate,封裝了各種方法,方便操作,它封裝了apache的kafka-client,不需要再導(dǎo)入client依賴,這篇文章主要介紹了SpringBoot集成Kafka 配置工具類,需要的朋友可以參考下
    2022-09-09
  • mybatisPlus更新字段值為null的解決方案

    mybatisPlus更新字段值為null的解決方案

    在使用mybatis-plus時(shí),發(fā)現(xiàn)當(dāng)前端傳入的值為null值時(shí),結(jié)果無(wú)論怎么操作后端都不執(zhí)行更新null字段的操作,下面這篇文章主要給大家介紹了關(guān)于mybatisPlus更新字段值為null的解決方案,需要的朋友可以參考下
    2023-04-04
  • java實(shí)現(xiàn)在SSM下使用支付寶掃碼支付功能

    java實(shí)現(xiàn)在SSM下使用支付寶掃碼支付功能

    這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)在SSM下使用支付寶掃碼支付功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-02-02

最新評(píng)論

宜都市| 土默特右旗| 曲靖市| 遵化市| 卓资县| 泰和县| 汾西县| 通山县| 上饶县| 岳普湖县| 岳普湖县| 揭东县| 广河县| 五常市| 长葛市| 永福县| 定结县| 丰宁| 延庆县| 蒙阴县| 揭西县| 涿州市| 河西区| 肇州县| 科技| 永年县| 扶绥县| 永城市| 双辽市| 育儿| 汉源县| 澄迈县| 阿尔山市| 特克斯县| 平南县| 长子县| 汨罗市| 宁蒗| 化州市| 武威市| 龙海市|