asyn4j java asynchronous method invocation framework

user_guide 
Updated Mar 4, 2012 by [email protected]
1.3 update

Optimized code
Added task persistence and recovery functions
Task invocation and callback as a whole
Example:
1. Call a common method
Main method

        public static void main(String[ ] args) {
                // Initialize asynchronous work service
                AsynService anycService = AsynServiceImpl.getService(300, 3000L, 100, 100,1000);
                //Asynchronous work buffer handler
                anycService.setWorkQueueFullHandler(new CacheAsynWorkHandler(100));
                //Service start And close the handler
                anycService.setServiceHandler(new FileAsynServiceHandler());
                //Asynchronous work execution exception handler
                anycService.setErrorAsynWorkHandler(new DefaultErrorAsynWorkHandler());
                // start the service
                asynService.init();
                // asynchronous callback object
                AsynCallBack back = new TargetBack();
                for (int i = 0; i < 1000; i++) {
                        // add Add asynchronous work - test method of TargetService, method parameter asynej+ i
                        asynService.addWork(TargetService.class, "test", new Object[] { "asyn4j" + i },new TargetBack());
                        //Instantiate the target object and then call
                       // TargetService targetService = new TargetService ();
                       //asynService.addWork(
                // targetService , "test",new Object[] { "asyn4j" + i }, new TargetBack());
                      
                }
        }
Callback method

//The callback needs to inherit the abstract
class AsynCallBack public class TargetBack extends AsynCallBack {

        @Override
        public void doNotify( ) {
                //Output the result of the asynchronous method call
                System.out.println(this.methodResult);

        }

}
Target object

//The asynchronous call object
public class TargetService {
        public String test(String name){
                System.out.println(name +" test is execute!");
                return name;
        }

}
2. Call the asynchronous method of Spring Bean
调用 Spring testBean 的 myName 方法

   applicationContext.xml 加入
    <bean id="springBeanUtil" class="com.googlecode.asyn4j.spring.AsynSpringUtil">
        </bean>

  <bean id="asynService" class="com.googlecode.asyn4j.spring.AsynServiceFactoryBean">
            <!--设置自定义相关参数-->
            <property name="maxCacheWork" value="100"></property>
                <property name="addWorkWaitTime" value="2000"></property>
                <property name="workThreadNum" value="3"></property>
                <property name="callbackThreadNum" value="2"></property>                 <!--Add related processors-->
                 <property name="closeServiceWaitTime" value="2000"></property>

                <property name="errorAsynWorkHandler">
                        <bean class="com.googlecode.asyn4j.core.handler.DefaultErrorAsynWorkHandler"/>
            </property>
                <property name="workQueueFullHandler">
                        <bean class="com.googlecode.asyn4j.core.handler.CacheAsynWorkHandler"/>
           </property>
<property name="asynServiceHandler">
                        <bean class="com.googlecode.asyn4j.core.handler.FileAsynServiceHandler"/>
           </property>
   </bean>


  public class TestMain {
       
        public AsynService asynService;

        public void setAsynService(AsynService asynService) {
                this.asynService = asynService;
        }
       
        public void maintest(){
                for(int i=0;i<10000;i++){
                        asynService.addWork("testBean", "myName",new Object[] { "panxiuyan" + i } );
                }
        }

}
3. Relevant processors
3.1 Asynchronous work buffer--(When the number of work in the work queue exceeds maxCacheWork, it is processed by the processor)
AsynService anycService = AsynServiceImpl.getService(300, 3000L, 100,
                                100);
                anycService. setWorkQueueFullHandler(new CacheAsynWorkHandler(100));
                anycService.init();
When there are more than 300 jobs in the work queue, the asynchronous work will be handled by CacheAsynWorkHandler;
the custom handler inherits the WorkQueueFullHandler abstract class
3.2 Service startup and shutdown handler--(call when service startup and shutdown)
      anycService.setCloseHander(new FileAsynServiceHandler("c:/asyn4j.data"));
set c:/asyn4j.data as persistent file FileAsynServiceHandler is of AsynServiceHandler An example persists tasks to a file, loads the file contents into memory when the system starts, and persists unexecuted tasks to a file when the system shuts down. You can refer to the source code to persist the task to another place (memcached).
The custom processor inherits the AsynServiceHandler abstract class.
3.3 Asynchronous work execution exception handler -- (handler when work execution exception occurs)
    anycService.setErrorAsynWorkHandler(new DefaultErrorAsynWorkHandler( ));
The custom processor inherits the ErrorAsynWorkHandler abstract class
3.4 All processors are optional configuration, it is recommended to implement your own processor according to your own business inheritance related classes
4. Asynchronous work priority is
divided into three levels WorkWeight.LOW, WorkWeight. MIDDLE, WorkWeight.HIGH Default priority is WorkWeight.MIDDLE.
API description
1. The default constructor
   AsynServiceImpl.getService();
the default parameters used are,

(maxCacheWork) maximum number of work queue cache jobs – 300 (default)
(addWorkWaitTime) add work wait time when work queue is full -- Long.MAX_VALUE (default)
(workThreadNum) asynchronous work execution thread pool size ---- CPU Number of cores/2 +1 (default value)
(callBackThreadNum) Callback execution thread pool size --- Number of CPU cores/2 (default value)
(closeServiceWaitTime) Service shutdown waiting time ---- 60000s (default value)
2. Customize Parameter constructor, the parameter order corresponds to the previous description
AsynServiceImpl.getService (1000, 1000L, 3, 2,60 * 1000);
AsynServiceImpl is thread-safe, an instance can be initialized, and all programs can be referenced again.

3. Set cache work queue processing Handler ( set before the init method is called)
public void setWorkQueueFullHandler(WorkQueueFullHandler workQueueFullHandler);
The system has a default handler CacheAsynWorkHandler It is recommended to implement your own handler, and you need to implement addAsynWork, process methods. process suggests to start a daemon thread to monitor.

4. Start the service
public void init();
5. Add async job API
/**
     * Add async job
     * @param tagerObject -- target object (can be Class, Object, String(spring))
     * @param method -- target method
     */
    public void addWork(Object tagerObject, String method);

    /**
     * Add asynchronous work
     * @ param tagerObject -- target object (can be Class, Object, String(spring))
     * @param method -- target method
     * @param params -- target method parameters
     */
    public void addWork(Object tagerObject, String method, Object[] params);

    /**
     * Add asynchronous work
     *
     *
     * @param tagerObject -- target object (can be Class, Object, String(spring))
     * @param method -- target method
     * @param asynCallBack -- callback object
     * @param params -- target method parameters
     */
    public void addWork(Object tagerObject, String method, Object[] params, AsynCallBack asynCallBack);

   
    /**
     * Add asynchronous work
     *
     *
     * @param tagerObject -- -- target object (can be Class,Object,String(spring))
     * @param method -- target method
     * @param asynCallBack -- callback object
     * @param params -- target method parameters
     * @param weight -- work weight
    
     */
    public void addWork(Object tagerObject , String method, Object[] params,AsynCallBack asynCallBack, WorkWeight weight);
   
   
    /**
     * Add asynchronous work
     * @param tagerObject --- target object (can be Class, Object, String(spring))
     * @param method -- target method
     * @param asynCallBack -- callback object
     * @param params -- target method parameters
     * @param weight -- work weight
     * @param cache -- if the target object is a class, whether to cache after instantiation
     */
    public void addWork(Object tagerObject, String method, Object[] params, AsynCallBack asynCallBack, WorkWeight weight,
            boolean cache);


    /**
     * Spring adds asynchronous work
     *
     * @param target -- target object BeanName
     * @param method - - target method
     * @param asynCallBack --callback object
     * @param params -- target method parameters
     * @param weight -- work weight
     */
    public void addWorkWithSpring( String target, String method, Object[] params, AsynCallBack asynCallBack, WorkWeight weight);

    /**
     * Add asynchronous work
     *
     * @param asynWork --- asynchronous work instance
     */
    public void addAsynWork(AsynWork asynWork);
       
6 .Get running status information
/**
         *
         * Get running status MAP
         * @return
         */
        public Map<String,Integer> getRunStatMap();

   Map key description
   total: the cumulative number of asynchronous jobs received
   execute: the number of asynchronous jobs
   executed callback: the execution callback Number
        /**
         * Get running status character information
         * @return
         */
        public String getRunStatInfo();
7. Call Spring Bean-based asynchronous methods
1.applicationContext.xml add

<bean id="springBeanUtil" class="com.googlecode.asyn4j.spring.AsynSpringUtil">
        </bean>
use the following methods to add Asynchronous work

   asynService.addWork("testBean", "myName", new Object[] { "asyn4j" + i });
VIII. Create Spring-based dependency Bean
asynService spring bean factory

   <bean id="asynService" class="com.googlecode.asyn4j.spring.AsynServiceFactoryBean">
            <!--Set custom related parameters-->
            <property name="maxCacheWork" value="100"></property>
                <property name="addWorkWaitTime" value="

                <property name="callbackThreadNum" value="2"></property>
                <!--添加相关处理器-->
                <property name="errorAsynWorkHandler">
                        <bean class="com.googlecode.asyn4j.core.handler.DefaultErrorAsynWorkHandler"/>
            </property>
                <property name="workQueueFullHandler">
                        <bean class="com.googlecode.asyn4j.core.handler.CacheAsynWorkHandler"/>
           </property>
   </bean>
九.Close the service      */      * Close the service and wait for 1 minute     /**     public void close(long waitTime);      */      * @ wait time      * Close the service and wait for waitTime seconds
   /**




   



    public void close();
10. Note that when
looking up the target method of asynchronous work, it is impossible to distinguish the method with the same name and the parameter is the inheritance relationship.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326996914&siteId=291194637