Redis-based spring task cluster configuration

Source: Internet
Author: User

Project from a single-node environment to a clustered environment, this time to ensure that the project's scheduled tasks at the same time can only be run in one of the servers in the cluster, but can not write dead on which server to run, how to achieve such a demand?

Ideas:

You can make a slice, scan a timed task, use the Redis cache to determine whether a task starts before the task starts, and because Redis is a single-threaded sequential command, you can use the Setnx method to determine if a value can be added before each scheduled task executes, and if it is added successfully, Note that this timed task is not executed, set the expiration time of key and let the timer task execute, if you can not add a value, it indicates that the scheduled task has been running on the other server, the method is returned. The expiration time of the key is greater than the sum of the method execution setnx in the cluster, not greater than the time interval of the scheduled task.

1. Define a custom annotation that configures the key, expiration time, repository, and so on for the scheduled task

 PackageCom.study.task;Importjava.lang.annotation.Documented;ImportJava.lang.annotation.ElementType;Importjava.lang.annotation.Retention;ImportJava.lang.annotation.RetentionPolicy;ImportJava.lang.annotation.Target, @Target ({elementtype.method}) @Retention (retentionpolicy.runtime) @Documented  Public@InterfaceTaskredisconfig {/**redis storage corresponding key*/String key ()default""; /**value of key corresponding to*/String value ()default"1"; /**Use the first Redis library to store the key*/String index ()default"0"; /**the expiration time of the key*/String timeout ()default"30"; /**whether to allow multiple nodes to run concurrently*/    BooleanIsconcurrent ()default false; }

2. Define a slice, scan a timed task, and use Redis's setnx before the scheduled task executes

 PackageCOM.STUDY.AOP;ImportJava.lang.reflect.Method;ImportOrg.aspectj.lang.ProceedingJoinPoint;ImportOrg.aspectj.lang.annotation.Around;ImportOrg.aspectj.lang.annotation.Aspect;ImportOrg.aspectj.lang.annotation.Pointcut;Importorg.aspectj.lang.reflect.MethodSignature;ImportOrg.springframework.context.annotation.EnableAspectJAutoProxy;Importorg.springframework.stereotype.Component;ImportCom.study.task.TaskRedisConfig;ImportCom.study.util.RedisUtil;ImportRedis.clients.jedis.Jedis, @Aspect @component@enableaspectjautoproxy Public classTASKAOP {@Pointcut ("@annotation (org.springframework.scheduling.annotation.Scheduled)")     Public voidpointcut () {}/*@Before ("Pointcut ()") public void Taskbefore (Joinpoint joinpoint) {String methodName = Joinpoint.getsignatu        Re (). GetName ();        System.out.println (MethodName);        Method method = (method) joinpoint.getthis ();        Method method = (method) Joinpoint.gettarget ();        if (Method.isannotationpresent (Taskredisconfig.class)) {System.out.println ("aaaaaaaaaa---------"); }    }*/@Around ("Pointcut ()")     Public voidTaskbefore (Proceedingjoinpoint joinpoint)throwsthrowable {String methodName=joinpoint.getsignature (). GetName ();        System.out.println (MethodName); Methodsignature methodsignature=(methodsignature) joinpoint.getsignature (); Method Method=Methodsignature.getmethod (); if(Method.isannotationpresent (Taskredisconfig.class) ) {Taskredisconfig TC= Method.getannotation (taskredisconfig.class); String Index=Tc.index (); Jedis Jedis=Redisutil.getjedis ();            Jedis.select (Integer.parseint (index)); String Key=Tc.key (); String value=Tc.value (); String Timeout=tc.timeout (); BooleanIsconcurrent =tc.isconcurrent (); if(!isconcurrent) {                //set success, return 1. Setting failed, returns 0.                 Longresult =jedis.setnx (key, value); if(result==1) {                    LongExresult =Jedis.expire (Key, Integer.parseint (timeout));                    Joinpoint.proceed ();                Jedis.close (); }Else {                    return; }            }                    }    }}

3. Write a timed task class for testing

 PackageCom.study.task;Importorg.springframework.scheduling.annotation.Scheduled;ImportOrg.springframework.stereotype.Service;Importorg.springframework.transaction.annotation.Transactional; @Service Public classsimpletask {@Scheduled (cron= "0/10 * * * *?") @TaskRedisConfig (Key= "Simpletask:methodone", timeout= "9", index= "2") @Transactional Public voidMethodOne () {System.out.println ("MethodOne----, Time:" + system.currenttimemillis ()/1000); } @Scheduled (Cron= "0/20 * * * *?") @TaskRedisConfig (Key= "Simpletask:methodtwo", timeout= ", index=" 2 ")     Public voidMethodtwo () {System.out.println ("Methodtwo----, Time:" + system.currenttimemillis ()/1000); }}

You can put the project into two workspaces, start the two items separately with two eclipse to see the results

Code git Address: https://gitee.com/sjcq/redis.git

Redis-based spring task cluster configuration

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.