Java thread Update cache in real time

Source: Internet
Author: User
Tags aop set time thread class

Java thread Update cache in real time


Nonsense not to say, directly on the code, we have seen, feel and you do similar functions, take to use it, leave no message does not matter, after all, the programmer is not easy ah ...

SPRING+JDBC Framework

Step One: Configure the spring file, and when the Web program runs, initialize a class (in order for interns to understand better, I would say: "It means that when the program runs, it executes all the methods in a class," The great Gods don't spray, I'm a novice)

<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" xmlns:
	Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "Http://www.springframework.org/schema/context" xmlns:p= "http://www.springframework.org/schema/p" xsi:schemalocation= "http://www.springframework.org/schema/ Beans <span style= "White-space:pre" > </span>http://www.springframework.org/schema/beans/ Spring-beans-2.5.xsd <span style= "White-space:pre" > </span>http://www.springframework.org/schema/ Context <span style= "White-space:pre" > </span>http://www.springframework.org/schema/context/ Spring-context-2.5.xsd Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/ Spring-tx-2.5.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/ Spring-aop-2.5.xsd "xmlns:tx=" Http://www.springframework.org/schema/tx "xmlns:aop=" http:// Www.springframework.org/schema/aop ""; <!--initialization system parameters--> <bean id= "initialization" class= "Com.xtown.smartcity.Initialization" scope= "Singleton" init-method= "Init" > </bean> </beans>

The second step: Initialize the initialization class, this class inherits the Servletcontextaware is to be able to obtain inside some interface method, as to what use, requests the intern to inquire in detail the ServletContext is what, has what function, Or look at the spring document, which, when it is run, initializes the method in the initialization class through the spring configuration file, usually by implementing some of the features that the program will implement as soon as it starts running, such as real-time updates, threads, and so on.

/** * * Project name: Seautobizshow <br/> * Class name: Initializationservice <br (/>) Description: Initialize system parameters <br/> * Creator: P Anpan <br/> * Creation time: 2013-7-24 pm 07:42:58 <br/> * Modified by: Panpan <br/> * Modified: 2013-7-24 afternoon 07:42:58 <b R/> * Modification Note: <br/> * * @version/public class initialization implements Servletcontextaware {Servletcon
	Text context;
	
	@Resource Adminuserservice Adminuserservice;
	public void Setservletcontext (ServletContext context) {This.context = context;
		public void init () {//Everyone focus here is the method that the program must initialize at the beginning of the procedure, the method body can be written directly in this class, or its own encapsulation class to invoke.
		Initcontentpath ();
		Initres ();
		Initadminuser ();
	Cachemanager.runtask ()//This is my package of classes, but also I need the program to be executed at the beginning of the method, there are some static methods for my call, the following will be posted out for everyone to see. /** * Initialization project PATH/public void Initcontentpath () {/** Set project name */String ContextPath = Context.getcontextpath (). R
		Eplace (' \ \ ', '/');
		Context.setattribute ("path", ContextPath);
	Context.setattribute ("Webpath", Global.webpath); /** * * Method Name: Initres <br/> * Description: Initialize menu resource <br/> * Parameters: <br/> * <br/> * * @return void <br/> * @thr
	OWS */public void Initres () {resxmlparser.getinstance (). Geturiresources ();
	/** * Create background Super admin/public void Initadminuser () {adminuserservice.doinituser (); }

}


The third step: This is my encapsulated cache class, which encapsulates a number of methods to deal with caching, but also the first step of the spring configuration file initialization, the second step of the class inside, the third step of the encapsulation class method.

package Com.xtown.web.util.cache;


Import Java.util.HashMap;   
	  
    public class CacheManager {public static HashMap Cachemap = new HashMap (); Get cached.   
    Synchronous static method public static Object GetCache (String key) {return (Object) cachemap.get (key);   
    }//Load JSON cache public static void Putcache (String key, Object obj) {cachemap.put (key, obj); //Determine if there is a cache public synchronized static Boolean Hascache (String key) {return cachemap.contains   
    Key (key);   
    //Clear all cached public synchronized static void ClearAll () {cachemap.clear ();   
    //Clears the specified cache public synchronized static void Clearonly (String key) {cachemap.remove (key);   
    //Get the size of the cache public static int getcachesize () {return cachemap.size ();
		The public static void Runtask () {//This is the method that the class to invoke in the second step initializes.
	New Clearcachetask (). Start (); }
    
}


Fourth step: This is the third step to call the other class inside the method, this class is the thread class, when the program is run, the thread will execute, and always execute, set a good time to implement real-time update cache.

Package Com.xtown.web.util.cache;


public class Clearcachetask extends thread{//inheritance thread class <span style= "Font-family:arial, Helvetica, Sans-serif;" >Thread</span>

<span style= "White-space:pre" >	</span>        //Rewrite thread class Run method
		@ Override public
		Void Run () {
			try {(
				true) {//loop, when True, executes the following code block
					System.out.println ("******** cachemap******************* ");
					Thread.Sleep (5*60*1000)//Set time, here is set 5 minutes, the format is: 24*60*60*1000 (time * minutes * seconds * milliseconds)
					CacheManager.cacheMap.clear ();// This is the method that invokes the cleanup cache inside the encapsulated class
				}
				
			catch (Interruptedexception e) {
				e.printstacktrace ()
			;
    }}


Fifth step: is to implement the logic function, when the user input parameters, the following method will be executed.

Package com.xtown.smartcity.controller.mobile;
Import java.util.ArrayList;
Import java.util.Collections;
Import Java.util.Comparator;

Import java.util.List;
Import Javax.annotation.Resource;
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse;
Import Org.springframework.stereotype.Controller;

Import org.springframework.web.bind.annotation.RequestMapping;
Import Com.google.gson.JsonArray;
Import Com.google.gson.JsonObject;
Import Com.xtown.smartcity.DataTypes;
Import Com.xtown.smartcity.DeviceInfo;
Import Com.xtown.smartcity.Globals;
Import Com.xtown.smartcity.XpsActionParams;
Import com.xtown.smartcity.info.App;
Import com.xtown.smartcity.info.City;
Import com.xtown.smartcity.info.Content;
Import com.xtown.smartcity.info.Favorites;
Import Com.xtown.smartcity.info.Msgready;
Import Com.xtown.smartcity.info.Service;
Import Com.xtown.smartcity.info.Topics;
Import Com.xtown.smartcity.info.Topicstyle;
Import Com.xtown.smartcity.info.UserInfo; ImporT com.xtown.smartcity.info.Usermsg;
Import Com.xtown.smartcity.service.MobileApiService;
Import Com.xtown.smartcity.service.MobileSsoService;
Import Com.xtown.web.util.DateTimeUtil;
Import Com.xtown.web.util.NumberUtil;
Import Com.xtown.web.util.StringUtil;

Import Com.xtown.web.util.cache.CacheManager; /** * Interface * @author Liangli */@Controller @RequestMapping ("/mobile/city/*") public class Citycontroller extends Base
	Mobilecontroller {@Resource Mobileapiservice service;

	@Resource Mobilessoservice SSO; /** * City Public Information * @param request * @param response * @return * * * @RequestMapping ("public") publicly void Publicinfos (HttpServletRequest request, httpservletresponse response) throws Exception {//To determine if there is a cache if (!) Cachemanager.hascache (key)) {//here is where you want to implement the logic, you need to cache what data, to check, find the data, call the CacheManager package inside the method, the data cache, the cache inside no data, It's going to execute here.
		Cachemanager.putcache (Key, jo.tostring ());//encapsulate the JSON data that the load in the package class needs to cache.
		}else{
		//Here is if there is data in the cache, will always take the data from the cache, as to how to write, it depends on your own, generally are first from the cache to take out the JSON data, and then output to the client.
		Outputjson ((String) Cachemanager.getcache (key), response)//The code is to enter the JSON data, and the first argument inside is to get the data from the cache that you previously cached, The second parameter does not need to say, the meaning is very obvious, is the response, this is the novice novice all one parameter, I do not have to say, does not understand goes to find the Niang to check HttpServletResponse
		}

	}
}

The whole realization of a Java real-time update cache data The problem is this, I for those interns, and just graduated from the work of the programmer, to rearrange the ideas, I did not do so, I do have enough complexity, is in the spring configuration file with a lot of, And then write a lot of code to achieve, the end of the final or to the manager of the head of a malicious scold a meal, then told me to use the threading method, step-by-step implementation, to the end, I just understand, simple, very simple, only to write their own less than 30 code on the deal, than I configure the spring file with the death, Then write a lot of code to achieve a much better, there is the development experience of the manager is different, put the fart is fragrant. Okay, so much nonsense, I'll tidy up the following:

The first step is to configure the spring file, initialize initialization, and the second step is to create a initialization implementation servletcontextaware that invokes the method inside the encapsulated class in the third step. The third step encapsulates a cache class, which writes some loading caches and clears the cache for invocation. The fourth step is to build a Clearcachetask class to inherit the thread class, rewrite the Run method, and implement some functions that need to be implemented in the Run method, such as the need to clear the cache, in which the third step cache class inside the method can be called. The fifth and final step is to implement the logic, out of the data that you need to look up, and then call the methods in the encapsulated cache class.


Description: This article for interns and just out of work programmers encounter this aspect of the function, to refer to. The great God, see also don't spray, I am not fraught, I also just graduated from the workers, just to write their own independent opinion, for interns and just out of the working programmer reference Just, there are errors, welcome to point out, so I can learn, thank you ...



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.