Scheduled Task Management Center (dubbo + spring)-How far can we go series 47 and dubbo + spring?

Source: Internet
Author: User

Scheduled Task Management Center (dubbo + spring)-How far can we go series 47 and dubbo + spring?
How far can we go? series 47

Nonsense:

In another year's New Year, I don't know how much you paid in the previous year and how much you learned? Maybe you are thinking about how much bonus the boss will pay, maybe you are thinking about which company to invest in next year.

It is indeed a great opportunity to make a summary at this time point.

At the end of the year, companies will always comment on performance and pull out your transcript. Do you want to say: go to your mom's transcript, I am not your student, I am not working hard to look at your face! Of course, the premise for you to say this is: you are a good B, if not, you can also think about it, and then silently change B.

Most of my friends and colleagues are people floating in the city. We strive to live better, think about our own life, and admire ourselves and choose this industry, trying to change the world.

So come on, everybody!

What new year do programmers have? Not enough time to write bugs!

Finally, I wish you a friend who saw this text:Good health, family fun, good luck, The company is listed.

Subject:

Generally, it is very easy to start a scheduled task. spring can run the task by writing an annotation, or there are many other jar support for the scheduled task of a single application.

A conventional scenario:A system generally consists of many business modules. These business modules are encapsulated into independently deployed applications for splitting and independent maintenance. Each business module has its own scheduled tasks to run. Generally, it relies on its own business data and logic and is naturally written in pigeon applications. In this case, the scheduled task management center must manage these scheduled tasks scattered in various business modules in a unified manner. The benefits of unified management are:1. The system-wide scheduled tasks are clear and easy to troubleshoot. 2. The task execution information is unified, such as logs. 3. The task Business Code development and task configuration are decoupled, the development and upgrade of task functions are concentrated in an application. Here, we roughly design a scheduled task management system. Roughly divided into the following three parts:1. Task Management System 2, Task Scheduling System 3, task logic of business implementation
Public class TaskSupport implements BeanPostProcessor, ApplicationListener <ApplicationContextEvent>, ApplicationContextAware {private static final Logger logger = LoggerFactory. getLogger (TaskSupport. class); private ApplicationContext applicationContext; private RegistryConfig registryConfig; private ApplicationConfig applicationConfig; private ProtocolConfig protocolConfig; // storage task bean private Map <String, Object> taskBeanMap = new HashMap <String, Object> (); // dubbo config private ServiceConfig <Object> serviceConfig; @ Override public Object postProcessBeforeInitialization (Object bean, String beanName) throws BeansException {return bean;} @ Override public Object postProcessAfterInitialization (Object bean, String beanName) throws BeansException {collectTaskBean (bean, beanName); return bea N;} private Object getTarget (Object bean) {Object target = bean; while (target instanceof Advised) {try {target = (Advised) bean ). getTargetSource (). getTarget () ;}catch (Exception e) {target = null; break ;}return target;} private void collectTaskBean (Object bean, String beanName) {Object target = getTarget (bean); if (target! = Null) {Class <?> Clazz = target. getClass (); if (! Clazz. isAnnotationPresent (Service. class) |! Clazz. isAnnotationPresent (Task. class) {return;} if (! TaskBeanMap. containsKey (beanName) {logger.info ("add task bean {}", beanName); taskBeanMap. put (beanName, bean) ;}}@ Override public void onApplicationEvent (ApplicationContextEvent event) {if (isCurrentApplicationContextRefresh (event) {exportTaskDispatcher ();}} @ Override public void setApplicationContext (ApplicationContext applicationContext) throws BeansException {this. applicationContext = ApplicationContext;}/*** expose the Task distributor service to the Task */protected void exportTaskDispatcher () {if (serviceConfig! = Null & serviceConfig. isExported () {return;} applicationConfig = applicationContext. getBean (ApplicationConfig. class); registryConfig = applicationContext. getBean ("soaRegistryConfig", RegistryConfig. class); protocolConfig = applicationContext. getBean (ProtocolConfig. class); TaskDispatcherImpl taskServiceProxyImpl = wireTaskServiceProxy (); exportServiceConfig (taskServiceProxyImpl);} protected vo Id unexportTaskDispatcher () {if (serviceConfig! = Null & serviceConfig. isExported () {serviceConfig. unexport () ;}} private TaskDispatcherImpl wireTaskServiceProxy () {AutowireCapableBeanFactory beanFactory = applicationContext. destroy (); DefaultListableBeanFactory defaultListableBeanFactory = (defalistlistablebeanfactory) beanFactory; TaskDispatcherImpl taskServiceProxy = new TaskDispatcherImpl (); // implement bean of ITaskDispatcher is loaded into spring bean containers, wait for the dubbo interface to expose taskServiceProxy = (TaskDispatcherImpl) beanFactory. initializeBean (taskServiceProxy, "taskServiceProxy"); // inject the filtered taskBeanMap to TaskDispatcherImpl. You can directly use taskServiceProxy. setTaskBeanMap (taskBeanMap); taskServiceProxy. setApplicationConfig (applicationConfig); taskServiceProxy. setRegistryConfig (registryConfig); defaultListableBeanFactory. registerSingleton ("taskServiceProxy", taskServiceProxy); return taskServiceProxy;}/*** dubbo interface exposed to the task scheduling system **/private void exportServiceConfig (Object proxy) {serviceConfig = new ServiceConfig <Object> (); serviceConfig. setApplication (applicationConfig); serviceConfig. setRegistry (registryConfig); serviceConfig. setProtocol (protocolConfig); // exposes this interface to serviceConfig. setInterface (ITaskDispatcher. class); serviceConfig. setRef (proxy); serviceConfig. setRetries (0); // The group of each business system is different. The dubbo attribute serviceConfig is fully used here. setGroup (applicationConfig. getName (); serviceConfig. export ();}/*** is the current context to prevent repeated loading and premature loading ** @ param event * @ return */private boolean isCurrentApplicationContextRefresh (ApplicationEvent event) {return event instanceof ContextRefreshedEvent & (ContextRefreshedEvent) event ). getApplicationContext () = applicationContext ;}}

In this way, all applications expose an ITaskDispatcher class method, but each group is different. The method defined by ITaskDispatcher:

public interface ITaskDispatcher {   public void dispatch(TaskInvokeInfoDto taskInvokeInfoDto);}

The dispatch method is used to schedule and trigger a task in the scheduling center. According to the definition in the TaskInvokeInfoDto parameter, You need to locate the method of the class of the application, what is the parameter of this method? locate it and execute it. This is the function that the dispatch will implement.

Let's take a look at the definition of TaskInvokeInfoDto:

Private String appName; // The application to be located. The dubbo group distinguishes private String beanName. // The private String methodName class to be located; // locate the method private String [] parameterTypes; // The parameter type of the method. If the method is overloaded, private String [] args; // The parameter value

Then the core code of dispatch:

Public void dispatch (TaskInvokeInfoDto taskInvokeInfoDto) {try {Method method = findMethod (taskInvokeInfoDto); Class <?> [] ParameterClazzs = method. getParameterTypes (); if (parameterClazzs. length = 0) {ReflectionUtils. invokeMethod (method, taskBeanMap. get (taskInvokeInfoDto. getBeanName ();} else {Object [] parameterObjs = new Object [parameterClazzs. length]; for (int I = 0; I <parameterClazzs. length; I ++) {parameterObjs [I] = Jackson. base (). readValue (taskInvokeInfoDto. getArgs () [I], parameterClazzs [I]);} Reflectio NUtils. invokeMethod (method, taskBeanMap. get (taskInvokeInfoDto. getBeanName (), parameterObjs) ;}} catch (Exception e) {logger. error ("execute error... ", e) ;}// the positioning logic private Method findMethod (TaskInvokeInfoDto taskInvokeInfoDto) {Object bean = taskBeanMap. get (taskInvokeInfoDto. getBeanName (); Method method = null; if (ArrayUtils. isEmpty (taskInvokeInfoDto. getParameterTypes () {method = Refle CtionUtils. findMethod (bean. getClass (), taskInvokeInfoDto. getMethodName ();} else {final int paramCount = taskInvokeInfoDto. getParameterTypes (). length; Class <?> [] ClazzArray = new Class <?> [ParamCount]; for (int I = 0; I <paramCount; I ++) {try {clazzArray [I] = ClassUtils. getClass (taskInvokeInfoDto. getParameterTypes () [I]);} catch (ClassNotFoundException e) {logger.info ("failed to create a class Object Based on a string of the parameter type", e); return null ;}} method = ReflectionUtils. findMethod (bean. getClass (), taskInvokeInfoDto. getMethodName (), clazzArray);} return method ;}

The core functions of the entire task center can be implemented by calling dubbo in the scheduling center to control task execution.

Of course, this is just a simple implementation, and there are many optimizations and extensions available, such as job log printing and collection, and job application survival status heartbeat monitoring.

I have seen an article about which network to blow B in the past. After playing for half a day, I carefully read the features he mentioned and the unimplemented features, people who have done this will feel that it is not difficult to do it, but they feel very good when people share it. In fact, they know in their own hearts that this system is everywhere. Although B is blowing, it will give us a variety of inspiration.

 

Summary:

1. Using the BeanPostProcessor of spring in the code to filter out the beans you need is a new technique. In "Request Routing to Business Method Design" (2) to filter bean map, another method is used. Do you have any other ideas?

2. Reflection-related APIs can be further studied.

 

Let's move on

----------------------------------------------------------------------

Hard work may fail, but not hard work will certainly fail.

 

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.