spring + redis 實現數據的緩存

一、實現目標java

  經過redis緩存數據。(目的不是加快查詢的速度,而是減小數據庫的負擔)  web

二、所需jar包redis

  

  注意:jdies和commons-pool兩個jar的版本是有對應關係的,注意引入jar包是要配對使用,不然將會報錯。由於 commons-pooljar的目錄根據版本的變化,目錄結構會變。前面的版本是org.apache.pool,然後面的版本是 org.apache.pool2...spring

style="background-color: #0098dd; color: white; font-size: 17px; font-weight: bold;"三、redis簡介數據庫

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

四、編碼實現緩存

1)、配置的文件(properties)app

  將那些常常要變化的參數配置成獨立的propertis,方便之後的修改ide

  redis.propertiesmemcached

複製代碼

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;

@Servicepublic 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;/*
 * 監聽器,用於項目啓動的時候初始化信息 */@Servicepublic 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注入,便可獲得原先的緩存類。

相關文章
相關標籤/搜索