# springaop&& Timer task simple implementation interface access into the table and timed task Interface Retry #
Spring aop
Spring 定时任务
代理模式深化
1. Table Design
2.Aop Main code
@Aspect @componentpublic class Aoputils implements Ordered {//current private static final Logger Logger = loggerfactory. GetLogger (Aoputils.class); public static String Aoplog_no_retren_value = "NONE RETURN"; @Value ("${interface address. URL}") Private String URL; @Autowired private Requestinfodao Requestinfodao; /** * API Interface log access record * Surround notification implementation * @param JP * @return */@Around ("Execution (* Com.*.*.modules.*.servic e.commonservice.* (..)) ") Public Object Logapimethod (Proceedingjoinpoint JP) throws Throwable {requestattributes RA = requestcontextholder.g Etrequestattributes (); Servletrequestattributes SRA = (servletrequestattributes) RA; Object rvt = null; Requestinfo requestinfo = new Requestinfo (); Mates with subsequent timed tasks retry the interface mechanism if (SRA = = null) {try {rvt = Jp.proceed (Jp.getargs ()); String params = ""; list<object> Filterargs = Lists.newarraylist (); Try{if (Jp.getargs ()!=null) {Arrays.stream (Jp.getargs ()). ForEach (Arg-and { if (! ( Arg instanceof HttpServletRequest | | Arg instanceof HttpServletResponse) {filterargs.add (ARG); } }); } params = (Filterargs.size () ==0)? "": jsonmapper.tojsonstring (Filterargs); }catch (Exception e) {params = filterargs+ ""; } String returnvalue = ""; try {returnvalue = Rvt==null? "": jsonmapper.tojsonstring (RVT); }catch (Exception e) {returnvalue = "return value is too long not displayed"; } requestinfo.setparam (params); Requestinfo.setreturnvalue (returnvalue); Requestinfo.setupdatedate (New Date ()); User user = New User ("Interface retry");Requestinfo.setupdateby (user); Requestinfo.setresult (TRUE); Requestinfo.seterrorresson (NULL); Requestinfodao.updatebyparams (info); return rvt; } catch (Throwable var6) {Requestinfo.setresult (false); Requestinfo.seterrorresson ("On-line Interface Access exception:" +var6.getmessage ()); Logger.error ("On-line Interface Access exception:", VAR6); }} HttpServletRequest request = Sra.getrequest (); Requestinfo.setresult (TRUE); try {rvt = Jp.proceed (Jp.getargs ()); } catch (Throwable var6) {Requestinfo.setresult (false); Requestinfo.seterrorresson ("On-line Interface Access exception:" +var6.getmessage ()); Logger.error ("On-line Interface Access exception:", VAR6); } String MethodName = Jp.getsignature (). GetName (); The parameter is written as a collection array, and the interface retries to convert String params = ""; list<object> Filterargs = Lists.newarraylist (); try {if (Jp.getargs ()!=null) { Arrays.stream (Jp.getargs ()). ForEach (ARG, {if (!) ( Arg instanceof HttpServletRequest | | Arg instanceof HttpServletResponse) {filterargs.add (ARG); } }); } params = (Filterargs.size () ==0)? "": jsonmapper.tojsonstring (Filterargs); }catch (Exception e) {params = filterargs+ ""; } String returnvalue = ""; if (Isshowreturnvalue (methodName)) {try {returnvalue = Rvt==null? "": jsonmapper.tojsonstring (RVT); }catch (Exception e) {returnvalue = "return value is too long not displayed"; }}else {returnvalue = "return value not shown"; } httpservletrequest HttpServletRequest = (httpservletrequest) request; String RequestUri = Httpservletrequest.getrequesturi (); String beanname = Jp.getthis (). GetClass (). Getsimplename (); int num = Beanname.indexof ("$$"); Beanname = BeaNname.substring (0, 1). toLowerCase () + beanname.substring (1, NUM); Requestinfo.setid (Idgen.uuid ()); Requestinfo.setbeanname (Beanname); Requestinfo.setmethod (MethodName); Requestinfo.setparam (params); Requestinfo.setrequesturl (Url+requesturi); Requestinfo.setreturnvalue (returnvalue); Requestinfo.setcreatedate (New Date ()); Requestinfo.setupdatedate (New Date ()); Whether the interface is repeatable Method Aopmethod = ((methodsignature) jp.getsignature ()). GetMethod (); Method m = Jp.gettarget (). GetClass (). Getdeclaredmethod (MethodName, Aopmethod.getparametertypes ()); Interfacerepeatflag Interfacerepeatflag = m.getannotation (Interfacerepeatflag.class); if (Interfacerepeatflag = = null) {Requestinfo.setrepeatflag (false); }else {Requestinfo.setrepeatflag (Interfacerepeatflag.value ()); User user = new user (); User.setid ("interface Call"); Requestinfo.setcreateby (user); RequestinfO.setupdateby (user); if (Requestinfodao! = null) {Requestinfodao.insert (requestinfo); } return RVT; } Private Boolean Isshowreturnvalue (String methodName) {list<string> debugroles = arrays.aslist (aoplog_no _retren_value.split (",")); for (String debugrole:debugroles) {if (! Stringutils.isblank (methodName) && methodname.indexof (debugrole) = = 0) {return f Alse; }} return true; } @Override public int getorder () {return 1001; }}
3. Scheduled Task Configuration
<bean name= "Schedulerfactory" class= "Org.springframework.scheduling.quartz.SchedulerFactoryBean" > <!-- Define the data source, the data source needs to quzrtz the table of the cluster--<property name= "DataSource" > <ref bean= "DataSource"/> </pr operty> <!--Specify the key for the spring container if you do not set the Jobmap in the job to get the spring container--<property name= "Applicationcontextsche Dulercontextkey "value=" Applicationcontextkey "/> <!--specify spring configuration related information--<property name=" Configlocatio N "value=" Classpath:quartz.properties "/> <!--specify triggers, you can specify multiple--<property name=" triggers "> < ;list> <ref bean= "Interfacejobtrigger"/> </list> </property></bean><!-- Define task--><bean id= "Interfacejob" class= "Com.*.*.modules.quzrtz.service.interfacejob"/><bean id= " Interfacejobdetail "class=" Org.springframework.scheduling.quartz.JobDetailBean "> <property name=" Jobclass " > < proxy class for tasks above!--(self-implemented)--<value>com.*.*.modules.quzrtz.scheduler.interfacejobschedule</value> </property> <property name= "description" > <value> timed Task Interface retry </value> </property> <property name= "Jobdataasmap" > <map> <!--The actual task Beanname, fill in Eventmonitorservice beanname and <entry key= "Targeto Bject "value=" Interfacejob "/> <!--to execute which method in the bean--<entry key=" Targetmethod "value=" re Peatinterface "/> </map> </property></bean><bean id=" Interfacejobtrigger "class=" Org.spr Ingframework.scheduling.quartz.CronTriggerBean "> <property name=" Jobdetail "> <!--task Agent Bean name--&G T <ref bean= "Interfacejobdetail"/> </property> <property name= "description" > <!--task broker Bea N Name-<value> timed task interface retry </value> </property> <property name= "Cronexpression" > <!--configuration expression-<value>0 0/1 * * * *?</value> </property></bean>
4. Scheduled Tasks
@Transactional (readOnly = false) public void Repeatinterface () {requestinfo requestinfo = new Requestinfo (); Requestinfo.setrepeatflag (TRUE); Requestinfo.setresult (FALSE); list<requestinfo> requestinfolist = requestinfodao.findalllist (Requestinfo); for (Requestinfo requestinfo:requestinfolist) {String paramstr = Requestinfo.getparam (); String beanstr = Requestinfo.getbeanname (); String methodstr = Requestinfo.getmethod (); try {Object obj = Springcontextholder.getbean (BEANSTR); Method m = null; Method[] methods = Obj.getclass (). GetMethods (); if (Methods! = null && methods.length > 0) {for (Method method:methods) {if (Method.getname (). Equals (METHODSTR)) {m = method; Break }}} Class Paramcls = M.getparametertypes () [0]; list<object> params =Jsonarray.parsearray (PARAMSTR); Methodutils.invokeexactmethod (obj, Methodstr, Json.parseobject (jsonobject.tojsonstring (params.get (0)), ParamCls)) ; }catch (Exception e) {e.printstacktrace (); Logger.error ("Interface retry: failed, reason for failure:" +e.getmessage ()); Continue } logger.info ("Interface Retry succeeded: class name" +beanstr+ "; Method:" +methodstr+ "; parameter:" +paramstr+ "; end retry"); }}
5. Timed Task Scheduler-timed task Agent
public class Interfacejobschedule extends Quartzjobbean {private Logger Logger = Loggerfactory.getlogger (interfacejobs Chedule.class); Private String TargetObject; Private String Targetmethod; @Override protected void Executeinternal (Jobexecutioncontext context) throws Jobexecutionexception {try { Object otargetobject = Springcontextholder.getbean (TargetObject); Method m = null; Method[] methods = Otargetobject.getclass (). GetMethods (); if (Methods! = null && methods.length > 0) {for (Method method:methods) { if (Method.getname (). Equals (Targetmethod)) {m = method; Break }} m.invoke (Otargetobject, New object[]{}); }} catch (Exception e) {logger.error ("Interfacejobschedule Exception:", e); }}/** * @param targetObject the TargetobjECT to set */public void Settargetobject (String targetObject) {this.targetobject = TargetObject; }/** * @param targetmethod the Targetmethod to set */public void Settargetmethod (String targetmethod) { This.targetmethod = Targetmethod; }}
6. Interface Retry annotations
@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface InterfaceRepeatFlag { public boolean value() default true;}
7. Learning Summary
Spring AOP核心是代理模式,可见代理模式的拓展性有多强,有业务的代码才会有收获,试一试,收获颇多
springaop&& Timer task simple implementation Interface Access table and timed task interface retry