Spring + Redis implements data caching

Source: Internet
Author: User
Tags configuration settings memcached

1. Achieve the goal

Data is cached through Redis. (The goal is not to speed up the query, but to reduce the burden on the database)

2, the required jar package

  

Note: The version of the jdies and Commons-pool two jar has a corresponding relationship, note that the introduction of the jar package is to be paired with, otherwise it will be an error. The directory structure will change because the Commons-pooljar directory changes according to the version. The previous version is Org.apache.pool, and the later version is org.apache.pool2 ...

Style= "Color:white; font-size:17px; Font-weight:bold; " 3. Introduction to Redis

Redis is a key-value storage system. Similar to memcached, it supports storing more value types, including string (string), list (linked list), set (set), Zset (sorted set-ordered collection), and hash (hash type). These data types support Push/pop, Add/remove, and intersection-set and difference sets, and richer operations, and these operations are atomic. Based on this, Redis supports sorting in a variety of different ways. As with memcached, data is cached in memory to ensure efficiency. The difference is that Redis periodically writes the updated data to disk or writes the modification to the appended record file, and on this basis implements the Master-slave (master-slave)

4. Code implementation

1), Configuration of the file (properties)

Configure the parameters that are often changed to be independent propertis, allowing for later modifications

Redis.properties

redis.hostname=127.0.0.1redis.port=6379redis.timeout=15000redis.usepool=trueredis.maxidle= 6redis.minevictableidletimemillis=300000redis.numtestsperevictionrun=3redis.timebetweenevictionrunsmillis= 60000

2), Spring-redis.xml

Configuration settings for Redis related parameters. The value of the parameter is derived from the properties file above

<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&          Gt <property name= "Minevictableidletimemillis" value= "300000" ></property> <property name= "Numtestsper Evictionrun "value=" 3 "></property> <property name=" Timebetweenevictionrunsmillis "value=" 60000 "&GT;&L          T;/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.timebetweenev Ictionrunsmillis} "></property> </bean> <bean id=" jedisconnectionfactory "class=" Org.springframew Ork.data.redis.connection.jedis.JedisConnectionFactory "destroy-method=" destroy "> <property name=" poolconfi G "ref=" Jedispoolconfig "></property> <property name=" HostName "value=" ${redis.hostname} "></prop  erty> <property name= "Port" value= "${redis.port}" ></property> <property name= "Timeout" Value= "${redis.timeout}" ></property> <property name= "Usepool" value= "${redis.usepool}" ></prope          rty> </bean> <bean id= "jedistemplate" class= "Org.springframework.data.redis.core.RedisTemplate" > <property name= "ConnectionFactory" ref= "jedisconnectionfactory" ></property> <property Nam   E= "Keyserializer" >           <bean class= "Org.springframework.data.redis.serializer.StringRedisSerializer"/> </property&gt          ; <property name= "ValueSerializer" > <bean class= "Org.springframework.data.redis.serializer.JdkSerializ   Ationredisserializer "/> </property> </bean> </beans>

3), Applicationcontext.xml

Spring's general configuration file, in which case the code

<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

To set the general profile of spring to load at project startup

    <context-param>        <param-name>contextConfigLocation</param-name>        <param-value> classpath*:/meta-inf/applicationcontext.xml</param-value><!--  -    </context-param>

5), Redis Cache tool Class

valueoperations--caching of basic data types and entity classes
Cache of Listoperations--list
Cache of Setoperations--set

Cache for 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;     /** * Cache Basic objects, Integer, String, entity class, etc. * @param key cache keys* @param value Cached values * @return Cached objects * * Public <T> valueoperations<string,t> SETCACHEOBJEC         T (String key,t value) {valueoperations<string,t> operation = Redistemplate.opsforvalue ();        Operation.set (Key,value);    return operation;     }/** * Gets the cached base object. * @param key Cache key Value * @param operation * Data corresponding to @return cache key * * Public <T> T GETCACHEOB Ject (String key/*,valueoperations<string,t> operation*/) {valueoperations<string,t> operation = Red         Istemplate.opsforvalue ();    return Operation.get (key); }/** * Cache list Data * @param key cache keys * @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; }/** * Gets the cached List object * @param key value of the key cache * @return The data corresponding to the cache key value * * Public <T> LIST&LT ;        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 object that caches data * /Public <T> boundsetoperations<string,t> setcacheset (String key,set<t> dataSet) {Boundset Operations<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; }/** * Gets the cached Set * @param key * @param operation * @return */public set<t> Getcachese        T (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; }/** * Cache 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; /** * Get Cached MAP * @param key * @param hashoperation * @return */public <T> map<st Ring,t> Getcachemap (String key/*,hashoperations<string,string,t> hashoperation*/) {Map<String, T&gt ;        Map = Redistemplate.opsforhash (). Entries (key);    /*map<string, t> map = hashoperation.entries (key); */return map; }/** * Cache map * @param key * @param dataMap * @return */Public < T> HashoperaTions<string,integer,t> Setcacheintegermap (String key,map<integer,t> dataMap) {hashoperations HashO        Perations = 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; /** * Get Cached MAP * @param key * @param hashoperation * @return */public <T> Map<in Teger,t> Getcacheintegermap (String key/*,hashoperations<string,string,t> hashoperation*/) {Map<Inte        GER, t> map = Redistemplate.opsforhash (). Entries (key);    /*map<string, t> map = hashoperation.entries (key); */return map;     }}

6), test

The test here is that when the project starts, it finds the country and city data in the database, caches it, and then the data out

6.1 Cache data at project startup

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 for initializing information during project startup */@ Servicepublic 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) {//spring When it is started cache information such as City and country if ( Event.getapplicationcontext (). GetDisplayName (). Equals ("Root webapplicationcontext")) {System.ouT.println ("\n\n\n_________\n\n cache data \ ________\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 (), Citylis            T.get (i)); } for (int i = 0; i < countrylistsize; i + +) {Countrymap.put (countr            Ylist.get (i). getcountry_id (), Countrylist.get (i));            } rediscache.setcacheintegermap ("CityMap", CityMap); Rediscache.setcacheintegeRMap ("Countrymap", Countrymap); }    }    }

6.2 Getting cached data

    @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));        }    }     
   

Since the bean configured in the configuration file by spring is singleton by default, only the autowired injection is required to get the original cache class.

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

Spring + Redis implements data caching

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.