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

詳解redis與spring的整合(使用緩存)

 更新時間:2017年03月29日 11:03:49   作者:奮斗,堅持  
本篇文章主要介紹了redis與spring的整合(使用緩存),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

1、實現(xiàn)目標

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

2、所需jar包

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

3、redis簡介

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

3、編碼實現(xiàn)

1)、配置的文件(properties)

將那些經(jīng)常要變化的參數(shù)配置成獨立的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ù)的值來自上面的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  ——基本數(shù)據(jù)類型和實體類的緩存

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 緩存鍵值對應的數(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 緩存的對象

 */

 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 緩存鍵值對應的數(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ù)的對象

 */

 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)、測試

這里測試我是在項目啟動的時候到數(shù)據(jù)庫中查找出國家和城市的數(shù)據(jù),進行緩存,之后將數(shù)據(jù)去除。

6.1  項目啟動時緩存數(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)聽器,用于項目啟動的時候初始化信息

 */

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

以上就是spring+redis實現(xiàn)數(shù)據(jù)緩存的方法,希望對大家的學習有所幫助。也希望大家多多支持腳本之家。

相關(guān)文章

  • SpringBoot學習篇之@Valid與@Validated的區(qū)別

    SpringBoot學習篇之@Valid與@Validated的區(qū)別

    @Valid是使用Hibernate?validation的時候使用,@Validated是只用Spring?Validator校驗機制使用,下面這篇文章主要給大家介紹了關(guān)于SpringBoot學習篇之@Valid與@Validated區(qū)別的相關(guān)資料,需要的朋友可以參考下
    2022-11-11
  • Java?基于Hutool實現(xiàn)DES加解密示例詳解

    Java?基于Hutool實現(xiàn)DES加解密示例詳解

    這篇文章主要介紹了Java基于Hutool實現(xiàn)DES加解密,本文通過示例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-08-08
  • Java中的synchronized關(guān)鍵字

    Java中的synchronized關(guān)鍵字

    這篇文章主要介紹了Java中的synchronized關(guān)鍵字,synchronized可以保證方法或代碼塊在運行時,同一時刻只有一個線程可以進入到臨界區(qū)(互斥性),同時它還保證了共享變量的內(nèi)存可見性,下面我們就來看看你文章對synchronized鎖的介紹,需要的朋友也可以參考一下
    2021-12-12
  • java多線程join()方法的作用和實現(xiàn)原理解析(應用場景)

    java多線程join()方法的作用和實現(xiàn)原理解析(應用場景)

    join方法主要是用于將當前線程掛起,等待其他線程結(jié)束后在執(zhí)行當前線程,本文通過應用場景分析代碼示例講解java多線程join()方法的作用和實現(xiàn)原理,感興趣的朋友一起看看吧
    2021-07-07
  • 如何使用Java實現(xiàn)指定概率的抽獎

    如何使用Java實現(xiàn)指定概率的抽獎

    這篇文章主要給大家介紹了關(guān)于如何使用Java實現(xiàn)指定概率的抽獎的相關(guān)資料,Java抽獎程序的基本原理是通過隨機數(shù)生成器來實現(xiàn)隨機抽獎的功能,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下
    2023-07-07
  • java二進制運算基礎(chǔ)知識點詳解

    java二進制運算基礎(chǔ)知識點詳解

    在本文里小編給大家分享了關(guān)于java二進制運算基礎(chǔ)知識點以及實例代碼內(nèi)容,需要的朋友們參考學習下。
    2019-08-08
  • Java可以寫android的應用程序嗎

    Java可以寫android的應用程序嗎

    在本篇文章里小編給大家整理的是一篇關(guān)于Java可以寫android的應用程序嗎的相關(guān)基礎(chǔ)文章,有興趣的朋友們可以學習下。
    2020-11-11
  • SpringMVC中controller接收json數(shù)據(jù)的方法

    SpringMVC中controller接收json數(shù)據(jù)的方法

    這篇文章主要為大家詳細介紹了SpringMVC中controller接收json數(shù)據(jù)的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-09-09
  • springboot的http.server.requests服務請求流程源碼

    springboot的http.server.requests服務請求流程源碼

    這篇文章主要為大家介紹了springboot的http.server.requests服務請求流程源碼,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-12-12
  • SpringBoot+MinIO實現(xiàn)對象存儲的示例詳解

    SpringBoot+MinIO實現(xiàn)對象存儲的示例詳解

    MinIO?是一個基于Apache?License?v2.0開源協(xié)議的對象存儲服務,它是一個非常輕量的服務,可以很簡單的和其他應用的結(jié)合,所以下面我們就來看看SpringBoot如何整合MinIO實現(xiàn)對象存儲吧
    2023-10-10

最新評論

新建县| 库尔勒市| 尉氏县| 鹿泉市| 萨嘎县| 剑河县| 炎陵县| 尉犁县| 延寿县| 来宾市| 古浪县| 抚顺市| 建德市| 英山县| 仪陇县| 博乐市| 旬阳县| 盐池县| 介休市| 大石桥市| 灵山县| 弥勒县| 区。| 论坛| 康乐县| 宝鸡市| 泸西县| 定远县| 肇东市| 沁水县| 板桥市| 玉林市| 探索| 资阳市| 炎陵县| 华阴市| 朔州市| 台州市| 微博| 额尔古纳市| 皋兰县|