Spring combines redis how to implement caching of data _java

Source: Internet
Author: User
Tags configuration settings int size memcached redis

1. Achieve the goal

Caching data by Redis. (The goal is not to speed up the query, but to reduce the burden on the database)

2, the required jar bag

 

Note: jdies and commons-pool two jar versions are related, note that the introduction of the jar package is to pair use, otherwise it will be an error. Because the directory structure of the Commons-pooljar is changed according to the version. The previous version is Org.apache.pool, and the later version is org.apache.pool2 ...

Style= "Background-color: #0098dd; Color:white; font-size:17px; Font-weight:bold; " 3, Redis Introduction

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

3, coding implementation

1), Configuration of the file (properties)

Configure those parameters that are often changed into separate propertis to facilitate later modifications 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 the related parameter configuration settings. The value of the parameter comes 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 > <property name= "minevictableidletimemillis" value= "300000" ></property> <property name= "Numtests" Perevictionrun "value=" 3 "></property> <property name=" Timebetweenevictionrunsmillis "value=" 60000 "> </property>--> <property name= "Maxidle" value= "${redis.maxidle}" ></property> <property na Me= "Minevictableidletimemillis" value= "${redis.minevictableidletimemillis}" ></property> <property Name= "Numtestsperevictionrun" value= "${redis.numtestsperevictionrun}" ></property> <propertyName= "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.springframe 
Work.data.redis.serializer.StringRedisSerializer "/> </property>  <property name= "ValueSerializer" > <bean class= " Org.springframework.data.redis.serializer.JdkSerializationRedisSerializer "/> </property> </bean> &  Lt;/beans>

3), Applicationcontext.xml

Spring's total 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

Set Spring's total configuration file 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

hashoperations The cache of the 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 Redistemp
 

 
 Late /** * Cache Basic objects, Integer, String, entity class, etc * @param key cache keysValue * @param value Cache * @return Cached object/public <T> valueoperations<string,t> setcacheobject (String ke 
  Y,t value) {valueoperations<string,t> operation = Redistemplate.opsforvalue ();
  Operation.set (Key,value);
 return operation;
  /** * Gets the underlying object of the cache. * @param key Cache key Value * @param operation * @return cache key value corresponding to the data/public <T> T getcacheobject (String key/*,value 
  Operations<string,t> operation*/) {valueoperations<string,t> operation = Redistemplate.opsforvalue ();
 return Operation.get (key); /** * Cache list Data * @param key cache value * @param dataList list data to be cached * @return cached objects/public <T> List Operations<string, t> setcachelist (String key,list<t> dataList) {listoperations listoperation = RedisTempl
  Ate.opsforlist ();
   if (null!= dataList) {int size = Datalist.size ();
   for (int i = 0; i < size; I + +) {Listoperation.rightpush (Key,datalist.get (i)); } returnListoperation; /** * Gets the cached List object * @param key Cache value * @return cache key values corresponding to the data * * Public <T> list<t> getcachelist (Str
  ing 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 * @param DataSet-Cached data * @return cached Data Objects/public <T> Boundsetoper Ations<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; /** * Gets 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; /** * Cache Map * @param key * @param datamap * @return/public <T> hashoperations<string,string,t& Gt
  Setcachemap (String key,map<string,t> datamap) {hashoperations hashoperations = Redistemplate.opsforhash (); if (null!= datamap) {for (map.entry<string, t> entry:dataMap.entrySet ()) {/*system.out.prin TLN ("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&Lt 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; /** * Cache Map * @param key * @param datamap * @return/public <T> Hashoperations<stri Ng,integer,t> Setcacheintegermap (String key,map<integer,t> datamap) {hashoperations HashOperations = redisTe
  Mplate.opsforhash (); if (null!= datamap) {for (Map.entry<integer, t> entry:dataMap.entrySet ()) {/*system.out.prin TLN ("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 <T> map<integer,t> getc Acheintegermap (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), test

This test I was in the project start-up time to the database to find out the country and the city data, cache, and then remove the data.

6.1 Cached 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 initialization information when the project starts/@Service public class Startaddcachelistener implements Applicationlistener<contextrefresh
 
 edevent> {//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 Cache City and country information when started (event.getapplic Ationcontext (). GetDisplayName (). Equals ("Root webapplicationcontext")) {System.out.println ("\n\n\n_________\n\ n cache data \ 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 (), Count
   Rylist.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));
  }
 } 

   

Because the bean configured by spring in the configuration file is by default a single case, the original cache class is only required through autowired injection.

The above is spring+redis to realize the data caching method, hope to be helpful to everybody's study.

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.