Spring + Redis implements data caching

Source: Internet
Author: User
Tags configuration settings

 1, achieve the target through Redis cache data. (The goal is not to speed up the query, but to reduce the burden on the database) 2, the required jar   NOTE: jdies and Commons-pool two jar version is the 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, Redis Introduction 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 modified operation to the appended record file, and implements the Master-slave (Master-Slave) 4, the Code implementation 1), The configured file (properties) configures the parameters that are often changed into separate propertis to facilitate subsequent modifications redis.propertiesredis.hostname=127.0.0.1redis.port= 6379redis.timeout=15000redis.usepool=trueredis.maxidle=6redis.minevictableidletimemillis= 300000redis.numtestsperevictionrun=3redis.timebetweenevictionrunsmillis=600002), Spring-redis.xmlredis configuration settings for the relevant parameters. The value of the parameter is derived from the properties file above  <beansxmlns= "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 "><beanid=" Jedispoolconfig "class=" Redis.clients.jedis.JedisPoolConfig "><propertyname=" Maxidle "value=" ${redis.maxidle} ">property>< Propertyname= "Minevictableidletimemillis" value= "${redis.minevictableidletimemillis}" >property>< Propertyname= "Numtestsperevictionrun" value= "${redis.numtestsperevictionrun}" >property><propertyname= " Timebetweenevictionrunsmillis "value=" ${redis.timebetweenevictionrunsmillis} ">property>bean><beanid = "Jedisconnectionfactory" class= "Org.springframework.data.redis.connection.jedis.JedisConnectionFactory" Destroy-method= "Destroy" ><propertyname= "Poolconfig" ref= "Jedispoolconfig" >property><propertyname = "HostName" value= "${redis.hostname}" >property><propertyname= "Port" value= "${redis.port}" >property ><propertyname= "Timeout" value= "${Redis.timeout} ">property><propertyname=" Usepool "value=" ${redis.usepool} ">property>bean>< Beanid= "Jedistemplate" class= "Org.springframework.data.redis.core.RedisTemplate" ><propertyname= " ConnectionFactory "ref=" Jedisconnectionfactory ">property><propertyname=" KeySerializer ">< beanclass= "Org.springframework.data.redis.serializer.StringRedisSerializer"/>property><propertyname= " ValueSerializer "><beanclass=" Org.springframework.data.redis.serializer.JdkSerializationRedisSerializer "/ &GT;PROPERTY&GT;BEAN&GT;BEANS&GT;3), applicationcontext.xmlspring General configuration file, in the inside if the code  <beanclass= " Org.springframework.beans.factory.config.PropertyPlaceholderConfigurer "><propertyname=" Systempropertiesmodename "value=" System_properties_mode_override "/><propertyname=" IgnoreResourceNotFound " Value= "true"/><propertyname= "locations" ><list><value>classpath*:/meta-inf/config/ Redis.propertiesvalue>list>property>bean><impoRtresource= "Spring-redis.xml"/>4), web. XML settings Spring general configuration file loaded at project startup <context-param><param-name>contextConfigLocationparam-name>< PARAM-VALUE&GT;CLASSPATH*:/META-INF/APPLICATIONCONTEXT.XMLPARAM-VALUE&GT;CONTEXT-PARAM&GT;5),  The Redis Cache tool class valueoperations--the cache of Listoperations--list cache Setoperations--set for the base data types and entity classes Hashoperations Map Cache Importjava.io.serializable;importjava.util.arraylist;importjava.util.hashmap;importjava.util.hashset; Importjava.util.iterator;importjava.util.list;importjava.util.map;importjava.util.set; importorg.springframework.beans.factory.annotation.Autowired; Importorg.springframework.beans.factory.annotation.Qualifier; Importorg.springframework.context.support.ClassPathXmlApplicationContext; Importorg.springframework.data.redis.core.BoundSetOperations; Importorg.springframework.data.redis.core.HashOperations; Importorg.springframework.data.redis.core.ListOperations; Importorg.springframework.data.redis.core.redistemplate;importorg.springframework.data.redis. Core. Setoperations;importorg.springframework.data.redis.core.valueoperations; Importorg.springframework.stereotype.Service; @ServicepublicclassRedisCacheUtil {@[email protected] (" Jedistemplate ") publicredistemplate redistemplate;/*** Cache Basic object, Integer, String, entity class, etc. * @param key cache keys * @param value Cached values * @return Cached Object */public valueoperations setcacheobject (String key,t value) {valueoperations operation = Redistemplate.opsforvalue (); Operation.set (key,value); returnoperation;} /*** gets the base object for the cache. * @param key Cache key value * @param operation* @return The data corresponding to the cache key value */public T getcacheobject (String key/*,valueoperations operation*/) {Valueoperations operation = Redistemplate.opsforvalue (); return Operation.get (key);} /*** Cache List Data * @param key cache keys * @param dataList the list data to be cached * @return Cached object */public listoperations setcachelist (String key, List 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 the key value of the key cache * @return The data corresponding to the cache key value */public list getcachelist (String key) {List dataList = new ArrayList ( ); Listoperations 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 boundsetoperations setcacheset (String key,set D Ataset) {Boundsetoperations setoperation = redistemplate.boundsetops (key);/*t[] T = (t[]) Dataset.toarray (); Setoperation.add (t); */iterator it = Dataset.iterator (); while (It.hasnext ()) {Setoperation.add (It.next ());} return setoperation;} /*** gets the cached set* @param key* @param operation* @return */public Set getcacheset (String key/*,boundsetoperations operation*/ ) {Set DataSet = new HashSet (); Boundsetoperations 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 hashoperations setcachemap (String key,map dataMap) { Hashoperations hashoperations = Redistemplate.opsforhash (); if (null! = DataMap) {for (Map.entry Entry:dataMap.entrySet ( ) {/*system.out.println ("Key =" + entry.getkey () + ", Value =" + Entry.getvalue ()); */hashoperations.put (Key,entry.getkey (), Entry.getvalue ());}} return hashoperations;} /*** gets the cached map* @param key* @param hashoperation* @return */public Map getcachemap (String key/*,hashoperations hashoperation*/) {Map map = Redistemplate.opsforhash (). Entries (key);/*map map = hashoperation.entries (key); */return Map;} /*** Cache map* @param key* @param datamap* @return */public hashoperations setcacheintegermap (String key,map dataMap) { Hashoperations hashoperations = Redistemplate.opsforhash (); if (null! = DataMap) {for (Map.entry Entry:dataMap.entrySet ( ) {/*system.out.println ("Key =" + entry.getkey () + ", Value =" + Entry.getvalue ()); */hashoperations.put (kEy,entry.getkey (), Entry.getvalue ());}} return hashoperations;} /*** gets the cached map* @param key* @param hashoperation* @return */public Map getcacheintegermap (String key/*,hashoperations hashoperation*/) {Map map = Redistemplate.opsforhash (). Entries (key);/*map map = hashoperation.entries (key); */ Returnmap;}} 6), Test here to test I was in the project when the start of the database to find out the country and city data, cache, then the data out 6.1 when the project started cache data importjava.util.hashmap;importjava.util.list; Importjava.util.map;importorg.apache.log4j.logger;importorg.springframework.beans.factory.annotation.autowired ; Importorg.springframework.context.ApplicationListener; Importorg.springframework.context.event.contextrefreshedevent;importorg.springframework.stereotype.service; importcom.test.model.city;importcom.test.model.country;importcom.zcr.test.user;/** Listener for initializing information when the project is started */@ Servicepublicclassstartaddcachelistener implementsapplicationlistener{//Log Privatefinallogger log= Logger.getlogger (Startaddcachelistener.class); @AutowiredprivateRedisCacheUtil rediscache;@ Autowiredprivatebrandstoreservice Brandstoreservice; @OverridepublicvoidonApplicationEvent (Contextrefreshedevent event) {//spring cache the city and country information if Event.getapplicationcontext (). GetDisplayName (). Equals ("Root webapplicationcontext")) {System.out.println ("\n\n\n _________\n\n cache data \ n \ ________\n\n\n\n "); List citylist = Brandstoreservice.selectallcitymessage (); List countrylist = Brandstoreservice.selectallcountrymessage (); Map CityMap = Newhashmap (); Map Countrymap = Newhashmap (); intcitylistsize = Citylist.size (); intcountrylistsize = Countrylist.size (); for (inti = 0; I & Lt Citylistsize; i + +) {citymap.put (Citylist.get (i). getcity_id (), Citylist.get (i));} for (inti = 0; i < countrylistsize; i + +) {countrymap.put (Countrylist.get (i). getcountry_id (), Countrylist.get (i));} Rediscache.setcacheintegermap ("CityMap", CityMap); Rediscache.setcacheintegermap ("Countrymap", Countrymap);}}} 6.2 Get Cache data @autowiredprivaterediscacheutil Rediscache; @RequestMapping ("Testgetcache") Publicvoidtestgetcache () {/* Map Countrymap = Rediscacheutil1.getcachemAP ("Country"); Map CityMap = Rediscacheutil.getcachemap ("City"), */map Countrymap = Rediscacheutil1.getcacheintegermap ("CountryMap") ; Map CityMap = Rediscacheutil.getcacheintegermap ("CityMap"); for (Intkey:countryMap.keySet ()) {System.out.println (" Key = "+ key +", value= "+ countrymap.get (key));} System.out.println ("------------City"): for (Intkey: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.

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.