spring + redis implements data caching

http://www.cnblogs.com/0201zcr/p/4987561.html

cache data through redis. (The purpose is not to speed up the query, but to reduce the burden on the database)  

2. The required jar package

  

  Note : The versions of the two jars jdies and commons-pool have a corresponding relationship. Note that the jar package must be used in pairs, otherwise it will be used in pairs. will report an error. Because the directory of commons-pooljar changes according to the version, the directory structure will change. The previous version is org.apache.pool, while the latter version is org.apache.pool2...

style="background-color: #0098dd; color: white; font-size: 17px; font-weight: bold;" 3. Introduction to

  redis Redis is a key-value storage system. Similar to Memcached, it supports relatively more value types for storage, including string (string), list (linked list), set (collection), zset (sorted set -- ordered collection) and hash (hash type). These data types all support push/pop, add/remove, intersection union and difference, and richer operations, and these operations are atomic. On this basis, redis supports sorting in various ways. Like memcached, data is cached in memory to ensure efficiency. The difference is that redis will periodically write updated data to disk or write modification operations to additional record files, and on this basis implements master-slave (master-slave)

4. Coding implementation

1), configuration files (properties)

  Configure those parameters that are often changed as independent properties to facilitate future modification of

  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
=60000Redis.timeBetweenEvictionRunsMillis=60000 -redis.xml Redis   related parameter configuration settings. The value of the parameter comes from the properties file above Copy code <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.

  The general configuration file of

xml
<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 cache tool class

ValueOperations - basic data types and entities Class cache
ListOperations - list cache
SetOperations - set cache

HashOperations Map cache

copy code
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import
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 cached key value
     * @param value cached value
     * @return cached object
     */
    public <T> ValueOperations<String,T> setCacheObject(String key,T value)
    {
       
        ValueOperations<String,T> operation = redisTemplate.opsForValue();
        operation.set(key,value);
        return operation;
    }
   
    /**
     * Get the cached base object.
     * @param key cache key value
     * @param operation
     * @return data corresponding to cache key value
     */
    public <T> T getCacheObject(String key/*,ValueOperations<String,T> operation*/)
    {
        ValueOperations<String,T> operation = redisTemplate.opsForValue();
        return operation.get(key);
    }
   
    /**
     * Cached List data
     * @param key cached key value
     * @param dataList List data to be cached
     * @return cached object
     */
    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;
    }
   
    /**
     * Get the cached list object
     * @param key the cached key value
     * @return the data corresponding to the cached key value
     */
    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;
    }
   
    /**
     * Cache Set
     * @param key cache key value
     * @param dataSet cached data
     * @return cached data object
     */
    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;
    }
   
    /**
     * Get the cached 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;      */      * @return      * @param hashOperation      * @param key      * Get the cached Map     /**
    }
   






    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;
    }
}
   
Copy code
6), test

  Here I go to the database to find out the country and city data when the project starts, Cache the data, and then remove the data.

6.1 Cache the data when the project starts.

Copy code
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;

/*
* Listener, used to initialize information when the project starts
*/
@Service
public class StartAddCacheListener implements ApplicationListener<ContextRefreshedEvent>
{
    //Log
    private final Logger log= Logger.getLogger(StartAddCacheListener. class);
   
    @Autowired
    private RedisCacheUtil<Object> redisCache;
   
    @Autowired
    private BrandStoreService brandStoreService;
   
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event)
    {
        //When spring starts, cache city and country information
        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)); Copy code     }    
        }


  Since the beans configured by Spring in the configuration file are singleton by default, the original cache class can be obtained only by injecting through Autowired.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326581422&siteId=291194637