Task execution method and device based on annotation driving mechanism, equipment and medium
Patent Information
- Application Number
- CN202611290910.7
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-08-25
- Publication Date
- 2026-10-30
AI Technical Summary
1. Spring @Async的代理限制:由于CGLIB代理的工作机制,同类中的内部调用、接口层注解等场景下@Async注解不生效,且不具备消息持久化和跨进程消费能力;
[0013]由以上技术方案可以看出,本发明能够在Spring容器的Bean工厂后处理阶段生成全局共享元信息,在代理生成前读取RPC接口上的注解,克服RPC框架生成代理后无法解析接口注解的缺陷,且运行阶段无需重复扫描、解析注解,降低了服务开销;在Bean后处理阶段生成二次代理Bean,不修改底层RPC框架原生代理逻辑,无需侵入RPC框架源码,兼容性强;在初始化后阶段能够动态注册得到消息队列基础设施,消除了人工配置错配风险;在服务运行阶段通过代理拦截将同步RPC调用无感转为异步消息投递,并序列化为携带类型标签的消息体,为消费端精准还原参数类型提供依据,解决了通用序列化场景下参数类型丢失、反序列化失败及上下文传播断裂问题;在消费阶段,依靠类型标签可靠还原调用参数,能够保障跨进程消息反序列化准确性,逐层穿透双层代理结构获取原始业务对象,并通过反射调用机制执行消息体所携带的RPC业务任务,提升了框架复用性。
Smart Images

Figure CN123011559A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of communication technology, and in particular to a task execution method, apparatus, device, and medium based on an annotation-driven mechanism. Background Technology
[0002] In current mainstream microservice architectures, inter-service communication commonly uses synchronous RPC (Remote Procedure Call). A key characteristic of synchronous calls is that the caller, after initiating a request, needs to block and wait for the service provider to return a result. In complex business systems such as supply chain finance, a single business operation often involves serial calls to multiple services (e.g., transaction confirmation, contract generation, notification push, bank integration, etc.). The overall process is time-consuming, and the caller's thread is occupied for extended periods. In high-concurrency scenarios, this can easily lead to thread pool exhaustion, cascading timeouts, and even service avalanche.
[0003] To address the above issues, existing asynchronous solutions mainly include: (1) Spring @Async annotation solution: The Spring framework provides the @Async annotation to implement asynchronous execution of methods. However, this solution has a known framework-level limitation: when a private method in the same class calls a public asynchronous method, the @Async annotation will not take effect due to Spring AOP (Aspect Oriented Programming) proxy mechanism (based on CGLIB (Code Generation Library) subclass proxy), and it will still be executed synchronously. In addition, @Async is essentially a local thread pool asynchronous operation and does not have the ability to persist messages, retry on failure, or consume across processes.
[0004] (2) Manually convert to a message-driven solution: Developers manually change the caller of the synchronous method to message sending logic and write the corresponding consumer processing class. This solution requires modifying each method that needs to be asynchronous, modifying the caller code, writing the message body DTO (Data Transfer Object), writing the consumer class, and declaring the queue and binding relationship in the configuration file. This is a lot of work and highly intrusive.
[0005] (3) Reactive programming solution: Adopt reactive frameworks such as Reactor (Project Reactor, the core library of reactive programming) / WebFlux (Spring Web on Reactive Stack, the Spring reactive web framework) to transform into non-blocking calls. However, this solution requires the replacement of the entire technology stack, which is incompatible with the existing blocking Dubbo (Apache DubboRPC Framework, the Apache Apache distributed remote call framework) ecosystem, and the transformation cost is extremely high.
[0006] Furthermore, in the Spring + Dubbo ecosystem, the business contract of Dubbo services is defined at the interface layer (such as the XxxProvider interface), and the implementation class (such as XxxProviderImpl) is annotated with @DubboService. When creating a Bean, the Spring framework uses CGLIB technology by default to generate a proxy object for the subclass of the implementation class. This proxy enhancement applies to the method call path of the implementation class. When developers declare custom annotations on interface methods, the CGLIB proxy's method interceptor cannot directly perceive the interface-level annotation information, causing aspect logic based on interface annotations to fail. This technical limitation makes it difficult for developers to achieve the effect of "changing the method execution behavior simply by adding annotations to interface methods" using standard AOP methods.
[0007] Based on the above analysis, the existing technology mainly has the following shortcomings: 1. Spring @Async proxy limitations: Due to the working mechanism of CGLIB proxy, the @Async annotation does not work in scenarios such as internal calls within the same class or interface layer annotations, and it does not have message persistence and cross-process consumption capabilities; 2. Manual modification is highly invasive: Changing synchronous calls to message-driven calls requires modifying the business code method by method, involving multiple changes such as caller modification, message body definition, consumer writing, and queue configuration declaration, resulting in high maintenance costs and violating the open / closed principle; 3. Rigid static declaration of message infrastructure: Traditional queues, bindings, and consumer listening containers are all statically declared in the configuration class using the @Bean method. The number of queues and their properties are fixed at compile time and cannot be dynamically adjusted based on annotation scanning results. 4. Type loss during cross-process parameter transmission: After Java method parameters are serialized to JSON, runtime type information is lost (e.g., interface types degenerate into concrete classes, Long degenerates into Integer), causing reflection calls to fail during deserialization on the consumer side due to type mismatch; 5. Distributed context propagation breaks: Context information such as the trace ID and multi-tenant domain name, which are automatically passed by the framework in synchronous RPC, will break at the process boundary after switching to message-driven architecture, lacking a configurable propagation mechanism. Summary of the Invention
[0008] In view of the above, it is necessary to provide a task execution method, apparatus, device and medium based on annotation-driven mechanism, which aims to optimize the task execution process based on annotation-driven mechanism.
[0009] A task execution method based on an annotation-driven mechanism, the task execution method based on an annotation-driven mechanism includes: In the post-processing phase of the Bean Factory in the Spring container, the scan results are obtained by reading the Remote Procedure Call (RPC) scan package path configuration. The classpath scanner filters out the implementation classes marked with RPC service annotations from the scan results, parses the asynchronous task annotations on the RPC interface methods corresponding to the implementation classes, and generates global shared metadata based on the asynchronous task annotations. In the Bean post-processing phase of the Spring container, the original Beans of the instantiated RPC service are traversed, and a secondary proxy wrapping of the Bean is performed based on the original Beans and the global shared metadata. An independent interception proxy layer is added to the outer layer of the proxy generated by the original RPC framework to form a two-layer proxy structure, resulting in a secondary proxy Bean. In the initialization phase of the Spring container, the message queue infrastructure is dynamically registered based on the asynchronous task annotation in the global shared metadata. During the service operation phase, the RPC call request is intercepted by the method interceptor in the secondary proxy bean, and when the asynchronous task annotation is matched by querying the global shared meta information, the method parameters of the RPC call request are serialized into a message body carrying a type label, and the message body is sent through the message queue infrastructure. During the consumption phase, when the message body is received by the message listener in the message queue infrastructure, the method parameters are obtained by restoring the type label carried by the message body. The two-layer proxy structure is penetrated layer by layer to obtain the target business object with complete aspect enhancement. The target business object is used as the execution subject to execute the RPC business task carried by the message body through the reflection invocation mechanism.
[0010] A task execution device based on an annotation-driven mechanism, characterized in that the task execution device based on the annotation-driven mechanism includes: The generation unit is used in the post-processing stage of the Bean Factory in the Spring container to read the Remote Procedure Call (RPC) scan package path configuration to obtain the scan results, filter out the implementation classes marked with RPC service annotations from the scan results through the classpath scanner, parse the asynchronous task annotations on the RPC interface methods corresponding to the implementation classes, and generate globally shared metadata based on the asynchronous task annotations. The execution unit is used to traverse the original beans of the instantiated RPC service during the Bean post-processing phase of the Spring container, and perform secondary proxy wrapping of the beans according to the original beans and the global shared meta information. An independent interception proxy layer is added to the outer layer of the proxy generated by the original RPC framework to form a two-layer proxy structure and obtain the secondary proxy bean. The registration unit is used to dynamically register the message queue infrastructure based on the asynchronous task annotation in the global shared meta-information during the initialization phase of the Spring container. The interception unit is used to intercept RPC call requests through the method interceptor in the secondary proxy bean during the service operation phase, and when the asynchronous task annotation is determined to be matched by querying the global shared meta information, serialize the method parameters of the RPC call request into a message body carrying a type label, and send the message body through the message queue infrastructure. The execution unit is also used in the consumption phase to, when the message body is received by the message listener in the message queue infrastructure, restore the method parameters based on the type label carried by the message body, penetrate the two-layer proxy structure layer by layer to obtain the target business object with complete aspect enhancement, and use the target business object as the execution subject to execute the RPC business task carried by the message body through the reflection call mechanism.
[0011] A computer device, the computer device comprising: A memory for storing at least one instruction; and a processor for executing the instructions stored in the memory to implement the annotation-driven task execution method.
[0012] A computer-readable storage medium storing at least one instruction, which is executed by a processor in a computer device to implement the annotation-driven task execution method.
[0013] As can be seen from the above technical solutions, this invention can generate globally shared metadata in the post-processing stage of the Bean factory in the Spring container, read annotations on the RPC interface before proxy generation, overcome the defect that the RPC framework cannot parse interface annotations after generating the proxy, and eliminate the need for repeated scanning and parsing of annotations during the runtime stage, thus reducing service overhead; it generates secondary proxy Beans in the Bean post-processing stage without modifying the underlying RPC framework's native proxy logic, without intruding into the RPC framework source code, and has strong compatibility; it can dynamically register message queue infrastructure in the initialization stage, eliminating the risk of manual configuration misconfiguration; during the service runtime stage, it seamlessly converts synchronous RPC calls into asynchronous message delivery through proxy interception, and serializes them into message bodies carrying type tags, providing a basis for the consumer to accurately restore parameter types, solving the problems of parameter type loss, deserialization failure, and context propagation breakage in general serialization scenarios; during the consumption stage, it can reliably restore call parameters by relying on type tags, ensuring the accuracy of cross-process message deserialization, penetrating the double-layer proxy structure layer by layer to obtain the original business object, and executing the RPC business task carried in the message body through the reflection call mechanism, thus improving the reusability of the framework. Attached Figure Description
[0014] Figure 1 This is a flowchart of a preferred embodiment of the task execution method based on the annotation-driven mechanism of the present invention.
[0015] Figure 2 This is a functional block diagram of a preferred embodiment of the task execution device based on the annotation-driven mechanism of the present invention.
[0016] Figure 3 This is a schematic diagram of the structure of a computer device that implements a preferred embodiment of the annotation-driven task execution method of the present invention. Detailed Implementation
[0017] To make the objectives, technical solutions, and advantages of this invention clearer, the invention will be described in detail below with reference to the accompanying drawings and specific embodiments.
[0018] like Figure 1 The diagram shown is a flowchart of a preferred embodiment of the annotation-driven task execution method of the present invention. The order of the steps in this flowchart can be changed, and some steps can be omitted, depending on different requirements.
[0019] The annotation-driven task execution method is applied to one or more computer devices. The computer device is a device that can automatically perform numerical calculations and / or information processing according to pre-set or stored instructions. Its hardware includes, but is not limited to, microprocessors, application-specific integrated circuits (ASICs), field-programmable gate arrays (FPGAs), digital signal processors (DSPs), embedded devices, etc.
[0020] The computer device can be any electronic product that can interact with the user, such as a personal computer, tablet computer, smartphone, personal digital assistant (PDA), interactive network television (IPTV), smart wearable device, etc.
[0021] The computer equipment may also include network equipment and / or user equipment. The network equipment includes, but is not limited to, a single network server, a server group consisting of multiple network servers, or a cloud based on cloud computing consisting of a large number of hosts or network servers.
[0022] The server can be a standalone server or a cloud server that provides basic cloud computing services such as cloud services, cloud databases, cloud computing, cloud functions, cloud storage, network services, cloud communication, middleware services, domain name services, security services, content delivery networks (CDN), and big data and artificial intelligence platforms.
[0023] Artificial intelligence (AI) is the theory, method, technology and application system that uses digital computers or machines controlled by digital computers to simulate, extend and expand human intelligence, perceive the environment, acquire knowledge and use knowledge to obtain the best results.
[0024] Foundational technologies for artificial intelligence generally include sensors, dedicated AI chips, cloud computing, distributed storage, big data processing, operating / interactive systems, and mechatronics. AI software technologies mainly encompass computer vision, robotics, biometrics, speech processing, natural language processing, and machine learning / deep learning.
[0025] The network in which the computer device is located includes, but is not limited to, the Internet, wide area network, metropolitan area network, local area network, and virtual private network (VPN).
[0026] S10, in the post-processing phase of the Bean factory in the Spring container, the scan results are obtained by reading the Remote Procedure Call (RPC) scan package path configuration. The classpath scanner filters out the implementation classes marked with RPC service annotations from the scan results, parses the asynchronous task annotations on the RPC interface methods corresponding to the implementation classes, and generates global shared metadata based on the asynchronous task annotations.
[0027] The asynchronous task annotation includes a link tracing continuity attribute, which the consumer uses to determine whether to restore the upstream link tracing identifier from the message body or generate a new link tracing identifier.
[0028] In this embodiment, generating globally shared metadata based on the asynchronous task annotation includes: Extract annotation metadata from each asynchronous task annotation; The annotation meta-information of each asynchronous task annotation is aggregated according to the Bean name and stored in the shared meta-information mapping to obtain the global shared meta-information.
[0029] The following example illustrates the overall implementation process of this step.
[0030] It can read the service scan package path configuration of the RPC framework (such as dubbo.scan.basePackages) from the Spring environment configuration and obtain one or more comma-separated package path strings. If the configuration is empty, it will be returned directly without any processing.
[0031] Construct a classpath scanner, `ClassPathScanningCandidateComponentProvider` (with the default filter disabled), and add an `AnnotationTypeFilter` to specify that only classes annotated with `@DubboService` will be scanned. Iterate through all the package paths obtained from the scan, call `findCandidateComponents` to scan for classes matching the criteria in each package, and collect the fully qualified names of all scanned classes into a `Set`. <string>In the set (definitionClassNameSet), it is used for subsequent matching.
[0032] Iterate through all registered BeanDefinitions in the Spring BeanFactory and retrieve the fully qualified class name corresponding to each Bean definition using getBeanClassName(). If the class name exists in step Set... <string>If the bean is in the collection, it indicates that it is an RPC service implementation class, and then subsequent annotation analysis will be performed.
[0033] Load the Class object of the implementing class using `Class.forName(beanClassName)`, retrieve all implemented interfaces using `getInterfaces()`, and iterate through all declared methods of each interface using `getDeclaredMethods()`. For each method, check if it is annotated with `@AsyncTaskTag`. If not marked, skip this method; If an annotation has been provided, the generated queue name follows the default rule of "implementation class abbreviation-method name" (e.g., OrderProviderImpl-processOrder). If the queueName (message queue name, type String, automatically generated: implementation class abbreviation-method name) attribute of the annotation is not empty, the value specified by the annotation will be used. The queue name, Spring Bean name, method name, and annotation instance are encapsulated into a metadata data object `AsyncTaskTagDto`, and then aggregated and stored in a shared mapping Map (HashMap) using the Bean name as the key. <String,List <asynctasktagdto>>), which refers to the globally shared metadata.
[0034] This shared map will serve as the input data source for the next two stages, with the three components sharing data by referencing the same map object.
[0035] The above process can be accomplished using an asynchronous task build factory postprocessor (AsyncTaskBuildFactoryPostProcessor) and by implementing the BeanFactoryPostProcessor interface of the Spring framework.
[0036] Through the above embodiments, global shared metadata can be generated in the earliest stage of Spring container startup, before all ordinary Beans are instantiated. Annotations on RPC interfaces can be read before the proxy is generated, overcoming the defect that the RPC framework cannot parse interface annotations after generating the proxy. Moreover, there is no need to repeatedly scan and parse annotations during the runtime phase, thus reducing service overhead.
[0037] Furthermore, it enables transparent, zero-intrusion conversion. Simply add an `@AsyncTaskTag` annotation to the RPC interface method to transparently convert the method from a synchronous call to message-driven asynchronous execution. No modification to the implementation class's business logic, the caller's code, or manual queue configuration is required. Only an asynchronous task annotation needs to be declared on the interface method, fully adhering to the open / closed principle.
[0038] S11, in the Bean post-processing stage of the Spring container, the original Bean of the instantiated RPC service is traversed, and the Bean secondary proxy wrapping is performed according to the original Bean and the global shared meta information. An independent interception proxy layer is added to the outer layer of the proxy generated by the original RPC framework to form a two-layer proxy structure, and the secondary proxy Bean is obtained.
[0039] Understandably, the Spring framework uses CGLIB (Code Generation Library) by default to generate proxy subclasses for implementation classes, and the proxy enhancement applies to the method call path of the implementation class. When annotations are declared on interface methods, the method interceptors of CGLIB proxies cannot detect interface-level annotation information.
[0040] This embodiment can solve the above problems by wrapping a custom proxy around the already initialized proxy bean, which is a secondary proxy method.
[0041] Specifically, the step of performing secondary proxy wrapping of the Bean based on the original Bean and the globally shared metadata, adding an independent interception proxy layer to the outer layer of the proxy generated by the original RPC framework to form a two-layer proxy structure, and obtaining the secondary proxy Bean includes: Based on the original bean name of the original bean, query the global shared meta information to filter out the target original bean that contains the asynchronous task annotation; The target original Bean is secondary proxied and wrapped using a proxy factory, and the method interceptor of the independent interception proxy layer is injected. Obtain the secondary proxy object generated by the proxy factory as the secondary proxy bean.
[0042] Specifically, the proxy bean that has been initialized in the application container is set as the proxy target of ProxyFactory, and the subclass proxy is generated using the CGLIB class proxy method, so that the annotations declared in the interface layer can be perceived by the interceptor through the method declaration class information.
[0043] This can be achieved by implementing the Spring framework's BeanPostProcessor interface and ApplicationContextAware interface based on the AsyncTaskProxyBeanPostProcessor.
[0044] The execution timing is after each Bean initialization is completed. The following example, continuing from the previous one, illustrates the overall implementation process of this step.
[0045] For example, in the `postProcessAfterInitialization` method, the shared Map generated by S10 is queried using the name of the current Bean (beanName). If no match is found (i.e., the Bean does not have any methods that need to be asynchronousized), the original Bean is returned directly without any processing.
[0046] If a match is found, extract the queue names of all asynchronous methods from the metadata list to form a Set. <string>Set(queueNameSet).
[0047] Create a ProxyFactory instance and configure the following key parameters: 1) setTarget(bean): Sets a Spring-initialized bean (which may be a proxy object generated by the Dubbo or Spring AOP framework) as the target to be proxied; 2) addAdvice(new DubboServiceInterceptor(queueNameSet)): Injects a custom method interceptor, passing in a set of queue names; 3) setProxyTargetClass(true): Specifies the use of CGLIB class proxy (instead of JDK dynamic proxy) to ensure that specific classes can be proxied, not just interfaces.
[0048] The `proxyFactory.getProxy()` method is called to generate a secondary proxy object, which is then returned to replace the original bean reference in the Spring container. Afterward, all calls to this bean will first pass through the method interceptor of the secondary proxy layer.
[0049] Runtime logic of the method interceptor (DubboServiceInterceptor, implementing the MethodInterceptor interface): When a method is invoked, the interceptor retrieves the short name of the declared class (getDeclaringClass().getSimpleName()) and the method name (getName()) from MethodInvocation, and concatenates them into an identifier string in the format "short name of class - method name".
[0050] Determine if the identifier string is in the queue name set passed in during construction: if not, call invocation.proceed() to pass it through to the original proxy chain and execute the original business logic; if it is, proceed to the subsequent asynchronous message sending process.
[0051] Generate a message routing key, following the rule "queue name-key".
[0052] Get the distributed trace ID of the current thread: Read X_TRACE_ID from MDC (Mapped Diagnostic Context), and if it is empty, generate a new TraceId using TraceIdUtils.genTraceIdNotCached().
[0053] Iterate through all arguments of the method call (invocation.getArguments()), and generate a message parameter data object (AsyncTaskMessageDto) for each argument, containing two fields: 1) paramData: Serializes the parameter object into a JSON string (JSONObject.toJSONString(argument)); 2) paramClassName: Records the fully qualified class name of the parameter object at runtime (argument.getClass().getName()).
[0054] All parameter data objects are arranged into a list in order, and then encapsulated together with the TraceId into a JSON message body.
[0055] The message is sent to the configured Topic Exchange and corresponding RoutingKey via RabbitTemplate, and then an empty object is returned directly without executing the original method (invocation.proceed() is not called). The caller receives an immediate return, and the actual method logic will be executed asynchronously by the consumer.
[0056] Through the above embodiments, a secondary proxy bean is generated in the bean post-processing stage without modifying the native proxy logic of the underlying RPC framework, without intruding into the RPC framework source code, and with strong compatibility.
[0057] Furthermore, it can overcome the limitations of AOP interception at the interface layer. By wrapping a custom proxy around the initialized proxy bean, a secondary proxy technique is used to overcome the technical limitation that Spring CGLIB proxies cannot be aware of interface layer annotations, enabling annotations declared on interface methods to be reliably intercepted and processed.
[0058] S12, after the initialization of the Spring container, the message queue infrastructure is dynamically registered based on the asynchronous task annotation in the global shared metadata.
[0059] In this embodiment, the step of dynamically registering the message queue infrastructure based on the asynchronous task annotation in the global shared metadata includes: Iterate through all metadata data objects in the global shared metadata, and perform queue registration and listener registration for each asynchronous method encountered, to obtain each queue and each listener; By combining each queue and each listener, the message queue infrastructure is obtained.
[0060] Specifically, when dynamically creating a queue, a single active consumer flag is set in the queue parameters according to the single-threaded consumer attribute of the annotation, to ensure that only one consumer receives messages from the queue at any given time.
[0061] One approach is to use an asynchronous task queue registry (AsyncTaskRegisterQueueBean), which executes the above processing after the bean is initialized via @PostConstruct.
[0062] The execution timing can be after the core beans in the Spring container (such as ConnectionFactory, TopicExchange, etc.) have completed initialization.
[0063] The following example illustrates the overall implementation process of this step.
[0064] For example: Iterate through all metadata data objects in the shared Map generated by S10, and perform two operations for each asynchronous method: queue registration and listener registration.
[0065] The queue registration process includes: Read the message exchange name configuration (spring.rabbitmq.template.exchange) from the Spring environment and validate that it is not empty; Retrieve all Beans of type TopicExchange from the Spring container, find the target exchange instance by name matching, and verify its existence; Construct queue parameters based on annotation attributes: If singleThreadConsumer (whether to enable single active consumer mode, type boolean, default value is true) = true, set x-single-active-consumer=true in the queue parameter Map (RabbitMQ natively supports the single active consumer feature, ensuring that only one consumer receives messages from the queue at any given time). Create a Queue object, passing in the queue name, persistence flag, exclusive flag, auto-delete flag, and a Map parameter; Create a Binding object to bind the queue to the target Topic Exchange, with the routing key being "queue name-key"; Register the Queue and Binding as Spring singleton beans using ConfigurableApplicationContext.getBeanFactory().registerSingleton().
[0066] The listener registration process includes: Obtain a ConnectionFactory instance from the Spring container; Create a SimpleMessageListenerContainer message listener container and configure the following properties: 1) Connection Factory: Use the connection factory configured by the system; 2) Listening queue: Set to the name of the queue corresponding to the current asynchronous method; 3) Message Listener: Create a generic message listener instance AsyncTaskListener (passing in metadata and ApplicationContext); 4) Initial number of consumers: Take the value of curryConsumerSize (initial number of concurrent consumers, type int, default value is 1) from the annotation; 5) Maximum number of consumers: Take the value of maxCurryConsumerSize (maximum number of concurrent consumers, type int, default value is 1) of the annotation; 6) Reject re-entry policy: Set to false (rejected messages will not be re-entered into the queue); 7) Confirmation Mode: Automatic Confirmation (AUTO); 8) Retry strategy: Configure RetryOperationsInterceptor, set the maximum number of retries, backoff interval, and recoverer (RejectAndDontRequeueRecoverer, which rejects and does not re-enqueue after retries are exhausted).
[0067] Register the listener container as a Spring singleton bean using registerSingleton.
[0068] Through the above embodiments, the message queue infrastructure can be dynamically registered in the post-initialization stage, eliminating the risk of misconfiguration due to manual configuration.
[0069] Furthermore, it enables automatic registration of message infrastructure: queues, exchanges, and consumer listening containers are dynamically created and registered when the container starts based on the annotation scanning results, achieving a zero-configuration experience of annotation declaration as queue registration, avoiding the tedious work of manually declaring a large number of Queue Beans in traditional solutions.
[0070] S13, during the service operation phase, the RPC call request is intercepted by the method interceptor in the secondary proxy bean, and when the asynchronous task annotation is matched by querying the global shared meta information, the method parameters of the RPC call request are serialized into a message body carrying a type label, and the message body is sent through the message queue infrastructure.
[0071] In this embodiment, serializing the method parameters of the RPC call request into a message body carrying a type label includes: The method parameters are serialized to obtain serialized parameters; The serialization parameters are embedded into parameter type tags used for deserialization and restoration of parameters on the consumer side to assemble the message body.
[0072] The message body contains a parameter array, where each element contains a JSON serialized string of the parameter content and the fully qualified name of the parameter runtime class.
[0073] In this embodiment, the method further includes: When the query of the global shared metadata determines that the asynchronous task annotation is not matched, the original Bean is passed through for invocation.
[0074] Specifically, it intercepts method calls targeting secondary proxy beans and, upon hitting an asynchronous call, stops synchronous execution and the caller's return strategy (void returns directly).
[0075] Through the above embodiments, synchronous RPC calls are seamlessly converted into asynchronous message delivery through proxy interception during the service operation phase, and serialized into a message body carrying type tags. This provides a basis for the consumer to accurately restore the parameter type, and solves the problems of parameter type loss, deserialization failure and context propagation breakage in general serialization scenarios.
[0076] S14, during the consumption phase, when the message body is received by the message listener in the message queue infrastructure, the method parameters are restored based on the type label carried by the message body. The two-layer proxy structure is penetrated layer by layer to obtain the target business object with complete aspect enhancement. The target business object is used as the execution subject, and the RPC business task carried by the message body is executed through the reflection call mechanism.
[0077] In this embodiment, executing the RPC service task carried in the message body via reflection invocation mechanism includes: Based on the target method identifier carried in the message body and the method parameters obtained by reconstruction, the corresponding RPC business task is executed on the target business object through the reflection invocation mechanism.
[0078] One approach is to use an asynchronous task listener (AsyncTaskListener) to implement the Spring AMQP MessageListener interface to complete the above processing.
[0079] The method to obtain the original Bean object by penetrating the secondary proxy layer is as follows: the Bean obtained from the container is forcibly converted to the Advised interface, and getTargetSource().getTarget() is called to obtain the original target object being proxied.
[0080] The following example illustrates the overall implementation process of this step.
[0081] Message deserialization: Check the Spring container for the existence of a custom MessageConverter Bean. If it exists, use the custom converter to convert the Message to a string; if it does not exist, use the default Jackson2JsonMessageConverter for conversion, and simultaneously generate a new TraceId and write it to MDC and TraceIdUtils. Read the current Profile from environment variables and map it to the tenant domain name to inject ArgumentsHolder (for multi-tenant data isolation).
[0082] Linked tracing context recovery: Read the `param` parameter array from the JSON message body. Check the `traceIdContinuous` attribute in the metadata (whether to continue the upstream `TraceId` across asynchronous boundaries, type boolean, default value `true`): If `true`, extract the `TraceId` passed in from the producer from the message body and write it to the current consumer thread's `MDC` and `TraceIdUtils` to achieve continuity of linked tracing across asynchronous boundaries; if `false`, retain the new `TraceId` generated in the previous message deserialization step.
[0083] To obtain the original Bean through the proxy: obtain a Bean reference from the Spring container by Bean name (at this time, it is a secondary proxy object), cast it to the Advised interface (all Spring AOP proxy objects implement this interface), and call getTargetSource().getTarget() to obtain the original business Bean object (containing the original various aspect enhancements) through the proxy layer.
[0084] Precise parameter type restoration: Traverse the parameter array in the message body and process it in the following two rounds: Round 1: For each parameter, load the parameter's Class object using Class.forName(paramClassName) to form a parameter type array Class.<?> []; Second round: For each parameter, deserialize the JSON string into a parameter value object with the correct target type using JSONObject.parseObject(paramData, aClass), and construct the parameter value array Object[].
[0085] Reflection invocation of the target method: Call beanWithAspect.getClass().getMethod(methodName, classArray) with the method name and an array of parameter types to get the target Method object, set setAccessible(true), and call method.invoke(beanWithAspect, paramObjArray) to execute the actual business logic.
[0086] Exception handling: If an exception occurs during execution, the error log is recorded and the exception is wrapped as a CommonException and thrown. The retry strategy and the restorer of the message listening container will handle the exception.
[0087] Through the above embodiments, during the consumption phase, the accuracy of cross-process message deserialization can be guaranteed by reliably restoring the call parameters based on the type tags; the original business object can be obtained by penetrating the double-layer proxy structure layer by layer, and the enhanced capabilities of Spring AOP aspects, transactions, interceptors, etc. are fully preserved when executing tasks, maintaining consistency with local synchronous call behavior; the RPC business tasks carried in the message body are executed through the reflection call mechanism, eliminating the need to write separate consumption processing logic for each asynchronous task; the original business interface implementation is reused, eliminating the need to develop separate asynchronous consumption business methods, and improving the reusability of business code.
[0088] Furthermore, tracing can be configurably propagated across asynchronous boundaries. It supports flexible configuration at the method level via the `traceIdContinuous` annotation attribute to either continue the upstream `TraceId` or generate a new `TraceId`, catering to both full-link tracing and independent task tracing needs.
[0089] In this embodiment, a two-layer serialization protocol combining type tags and ordered parameter arrays is also configured to solve the problem of type loss after cross-process transmission of parameters.
[0090] For example, the message body structure may include: { "X_TRACE_ID": "trace-2025-xxxx-xxxx", "param": [ { "paramData": "{\"orderId\":1001,\"amount\":\"100.00\"}", "paramClassName": "com.example.dto.OrderDTO" }, { "paramData": "12345", "paramClassName": "java.lang.Long" } ] } In the above structure, each parameter is split into two fields: paramData stores the serialized JSON string, and paramClassName stores the fully qualified class name of the parameter at runtime. The consumer first uses paramClassName to recover the exact Class object using Class.forName, and then uses that Class as the target type to deserialize paramData, ensuring accurate type restoration.
[0091] The above embodiments enable precise verification of parameter types. By using a two-field serialization protocol combining JSON content and the fully qualified class name, the problem of parameter type loss after JSON serialization is solved, ensuring that the consumer can deserialize with the correct parameter types and accurately match the target method signature.
[0092] In this embodiment, the core components executing each step can achieve cross-stage data transfer by sharing the same HashMap reference: `AsyncTaskConfiguration` (the configuration class) creates three components sequentially using the `@Bean` method. The first component, `AsyncTaskBuildFactoryPostProcessor`, holds a `beanNameMap` (such as HashMap instance A) and populates it with data in the `postProcessBeanFactory()` stage; the second component, `AsyncTaskProxyBeanPostProcessor`, obtains a reference to the same HashMap instance A through constructor injection and reads data in the `postProcessAfterInitialization()` stage; the third component, `AsyncTaskRegisterQueueBean`, also obtains a reference to the same HashMap instance A through constructor injection and reads data in the `@PostConstruct` stage. These three components execute sequentially at different stages of the Spring container lifecycle, achieving cross-stage collaboration through shared data structures.
[0093] The following example illustrates the basic application of this embodiment.
[0094] Suppose that in a supply chain finance system, there exists a transaction notification service interface TradeNotifyProvider and its implementation class TradeNotifyProviderImpl: / / Interface definition -- only need to add annotations to the interface methods public interface TradeNotifyProvider { @AsyncTaskTag(traceIdContinuous = true) void notifyBankResult(TradeResultDTO result); @AsyncTaskTag(curryConsumerSize = 3, maxCurryConsumerSize = 5, singleThreadConsumer = false) void sendEmailNotification(EmailDTO email); / / This method has no annotations and will be called synchronously. TradeDetailDTO queryTradeDetail(Long tradeId); } / / Implementation class -- no modifications required @DubboService public class TradeNotifyProviderImpl implements TradeNotifyProvider { @Override public void notifyBankResult(TradeResultDTO result) { / / Actual business logic: Call the bank's API to push the results } @Override public void sendEmailNotification(EmailDTO email) { / / Actual business logic: Send email notification } @Override public TradeDetailDTO queryTradeDetail(Long tradeId) { / / Actual business logic: Query transaction details return tradeDetailDTO; } } The automatic processing procedures during system startup include: 1. During the post-processing phase of the Spring container's Bean Factory, the TradeNotifyProviderImpl class, annotated with @DubboService, is scanned. Traversing the methods of its interface TradeNotifyProvider, it is found that the notifyBankResult and sendEmailNotification methods are annotated with @AsyncTaskTag, generating the following metadata: {queueName:"TradeNotifyProviderImpl-notifyBankResult", beanName:"tradeNotifyProviderImpl", methodName:"notifyBankResult"} and {queueName:"TradeNotifyProviderImpl-sendEmailNotification", beanName:"tradeNotifyProviderImpl", methodName:"sendEmailNotification"}.
[0095] 2. In the post-processing phase of the Spring container, the tradeNotifyProviderImpl bean is wrapped by a second proxy and a method interceptor is injected.
[0096] 3. During the initialization phase of the Spring container, dynamically register two Queues, two Bindings, and two SimpleMessageListenerContainers into the Spring container. The notifyBankResult queue is configured with a single active consumer (x-single-active-consumer=true), and the sendEmailNotification queue is set to have 3 initial consumers and a maximum of 5.
[0097] During the service runtime phase, runtime invocation behaviors include: When tradeNotifyProvider.notifyBankResult(result) is called, the secondary proxy interceptor hits the asynchronous flag, serializes the result into a message and sends it to the MQ, and the caller returns immediately; Similarly, when calling tradeNotifyProvider.sendEmailNotification(email), it is converted to an asynchronous message; When tradeNotifyProvider.queryTradeDetail(tradeId) is called, the interceptor is not hit, and the result is passed through to the original method for synchronous execution and return.
[0098] This embodiment also allows for custom queue names, such as: public interface ClearingProvider { @AsyncTaskTag(queueName = "clearing-settlement-queue", durable = true, traceIdContinuous = false) void processClearingResult(ClearingDTO clearing); } At this point, the queue name is the "clearing-settlement-queue" specified by the developer instead of the automatically generated default name, and the consumer will generate a new TraceId instead of continuing the upstream TraceId.
[0099] Here, `durable` indicates whether the queue is persistent; its type is boolean, and its default value is `true`.
[0100] Based on this embodiment, annotation attributes support declarative control of runtime behaviors such as single active consumer mode (ensuring thread safety), consumer concurrency configuration, and queue persistence strategy, thereby achieving fine-grained consumer behavior control. When adding a method that needs to be asynchronous, simply add the annotation, and the framework will automatically complete the full-link configuration without modifying the framework code. It also supports mixing synchronous and asynchronous methods in the same RPC service class, which has high scalability.
[0101] As can be seen from the above technical solutions, this invention can generate globally shared metadata in the post-processing stage of the Bean factory in the Spring container, read annotations on the RPC interface before proxy generation, overcome the defect that the RPC framework cannot parse interface annotations after generating the proxy, and eliminate the need for repeated scanning and parsing of annotations during the runtime stage, thus reducing service overhead; it generates secondary proxy Beans in the Bean post-processing stage without modifying the underlying RPC framework's native proxy logic, without intruding into the RPC framework source code, and has strong compatibility; it can dynamically register message queue infrastructure in the initialization stage, eliminating the risk of manual configuration misconfiguration; during the service runtime stage, it seamlessly converts synchronous RPC calls into asynchronous message delivery through proxy interception, and serializes them into message bodies carrying type tags, providing a basis for the consumer to accurately restore parameter types, solving the problems of parameter type loss, deserialization failure, and context propagation breakage in general serialization scenarios; during the consumption stage, it can reliably restore call parameters by relying on type tags, ensuring the accuracy of cross-process message deserialization, penetrating the double-layer proxy structure layer by layer to obtain the original business object, and executing the RPC business task carried in the message body through the reflection call mechanism, thus improving the reusability of the framework.
[0102] like Figure 2 The diagram shown is a functional block diagram of a preferred embodiment of the annotation-driven task execution device 11 of the present invention. The annotation-driven task execution device 11 includes a generation unit 110, an execution unit 111, a registration unit 112, and an interception unit 113. In this invention, a module / unit refers to a series of computer program segments that can be executed by a processor and perform a fixed function, and which are stored in memory. In this embodiment, the functions of each module / unit will be described in detail in subsequent embodiments.
[0103] The generation unit 110 is used to read the Remote Procedure Call (RPC) scan package path configuration to obtain the scan results during the post-processing stage of the Bean Factory in the Spring container, filter out the implementation classes marked with RPC service annotations from the scan results through the classpath scanner, parse the asynchronous task annotations on the RPC interface methods corresponding to the implementation classes, and generate global shared meta-information based on the asynchronous task annotations. The execution unit 111 is used to traverse the original beans of the instantiated RPC service during the Bean post-processing stage of the Spring container, and perform secondary proxy wrapping of the beans according to the original beans and the global shared meta information, adding an independent interception proxy layer to the outer layer of the proxy generated by the original RPC framework to form a two-layer proxy structure, and obtaining a secondary proxy bean. The registration unit 112 is used to dynamically register the message queue infrastructure based on the asynchronous task annotation in the global shared meta information during the initialization phase of the Spring container. The interception unit 113 is used to intercept RPC call requests through the method interceptor in the secondary proxy Bean during the service operation phase, and when the global shared meta information is queried to determine that the asynchronous task annotation is hit, serialize the method parameters of the RPC call request into a message body carrying a type label, and send the message body through the message queue infrastructure. The execution unit 111 is further configured to, during the consumption phase, when the message body is received by the message listener in the message queue infrastructure, restore the method parameters based on the type label carried by the message body, penetrate the two-layer proxy structure layer by layer, obtain the target business object with complete aspect enhancement, and use the target business object as the execution subject to execute the RPC business task carried by the message body through the reflection call mechanism.
[0104] As can be seen from the above technical solutions, this invention can generate globally shared metadata in the post-processing stage of the Bean factory in the Spring container, read annotations on the RPC interface before proxy generation, overcome the defect that the RPC framework cannot parse interface annotations after generating the proxy, and eliminate the need for repeated scanning and parsing of annotations during the runtime stage, thus reducing service overhead; it generates secondary proxy Beans in the Bean post-processing stage without modifying the underlying RPC framework's native proxy logic, without intruding into the RPC framework source code, and has strong compatibility; it can dynamically register message queue infrastructure in the initialization stage, eliminating the risk of manual configuration misconfiguration; during the service runtime stage, it seamlessly converts synchronous RPC calls into asynchronous message delivery through proxy interception, and serializes them into message bodies carrying type tags, providing a basis for the consumer to accurately restore parameter types, solving the problems of parameter type loss, deserialization failure, and context propagation breakage in general serialization scenarios; during the consumption stage, it can reliably restore call parameters by relying on type tags, ensuring the accuracy of cross-process message deserialization, penetrating the double-layer proxy structure layer by layer to obtain the original business object, and executing the RPC business task carried in the message body through the reflection call mechanism, thus improving the reusability of the framework.
[0105] like Figure 3 The diagram shown is a structural schematic of a computer device that implements a preferred embodiment of the annotation-driven task execution method of the present invention.
[0106] The computer device 1 may include a memory 12, a processor 13, and a bus (the arrow in the figure represents the bus), and may also include a computer program stored in the memory 12 and executable on the processor 13, such as a task execution program based on an annotation-driven mechanism.
[0107] Those skilled in the art will understand that the schematic diagram is merely an example of computer device 1 and does not constitute a limitation on computer device 1. Computer device 1 can be either a bus topology or a star topology. Computer device 1 may also include more or fewer other hardware or software than shown in the diagram, or different component arrangements. For example, computer device 1 may also include input / output devices, network access devices, etc.
[0108] It should be noted that the computer device 1 described is merely an example. Other existing or future electronic products that are adaptable to this invention should also be included within the scope of protection of this invention and are incorporated herein by reference.
[0109] The memory 12 includes at least one type of readable storage medium, such as flash memory, portable hard drive, multimedia card, card-type memory (e.g., SD or DX memory), magnetic memory, magnetic disk, optical disk, etc. In some embodiments, the memory 12 can be an internal storage unit of the computer device 1, such as a portable hard drive of the computer device 1. In other embodiments, the memory 12 can be an external storage device of the computer device 1, such as a plug-in portable hard drive, smart media card (SMC), secure digital card (SD), flash card, etc., equipped on the computer device 1. Furthermore, the memory 12 can include both internal storage units and external storage devices of the computer device 1. The memory 12 can be used not only to store application software and various types of data installed on the computer device 1, such as the code of task execution programs based on annotation-driven mechanisms, but also to temporarily store data that has been output or will be output.
[0110] In some embodiments, the processor 13 may be composed of integrated circuits, such as a single packaged integrated circuit or multiple integrated circuits packaged with the same or different functions, including combinations of one or more central processing units (CPUs), microprocessors, digital processing chips, graphics processors, and various control chips. The processor 13 is the control unit of the computer device 1, connecting various components of the computer device 1 via various interfaces and lines. It executes programs or modules stored in the memory 12 (e.g., executing task execution programs based on annotation-driven mechanisms) and calls data stored in the memory 12 to perform various functions of the computer device 1 and process data.
[0111] The processor 13 executes the operating system of the computer device 1 and various installed applications. The processor 13 executes the applications to implement the steps in the above-described annotation-driven task execution method embodiments, for example... Figure 1 The steps are shown.
[0112] For example, the computer program may be divided into one or more modules / units, which are stored in the memory 12 and executed by the processor 13 to complete the present invention. The one or more modules / units may be a series of computer-readable instruction segments capable of performing specific functions, which describe the execution process of the computer program in the computer device 1. For example, the computer program may be divided into a generation unit 110, an execution unit 111, a registration unit 112, and an interception unit 113.
[0113] The integrated unit implemented as a software functional module described above can be stored in a computer-readable storage medium. This software functional module, stored in a storage medium, includes several instructions to cause a computer device (which may be a personal computer, computer equipment, or network device, etc.) or processor to execute portions of the annotation-driven task execution method described in the various embodiments of this invention.
[0114] If the modules / units integrated in the computer device 1 are implemented as software functional units and sold or used as independent products, they can be stored in a computer-readable storage medium. Based on this understanding, all or part of the processes in the methods of the above embodiments of the present invention can also be implemented by a computer program instructing related hardware devices. The computer program can be stored in a computer-readable storage medium, and when executed by a processor, it can implement the steps of the various method embodiments described above.
[0115] The computer program includes computer program code, which may be in the form of source code, object code, executable file, or some intermediate form. The computer-readable medium may include: any entity or device capable of carrying the computer program code, recording media, USB flash drive, portable hard drive, magnetic disk, optical disk, computer memory, read-only memory (ROM), random access memory, etc.
[0116] The bus can be a Peripheral Component Interconnect (PCI) bus or an Extended Industry Standard Architecture (EISA) bus, etc. This bus can be divided into address bus, data bus, control bus, etc. For ease of representation, in... Figure 3 The bus is represented by only one straight line, but this does not mean that there is only one bus or one type of bus. The bus is configured to enable communication between the memory 12 and at least one processor 13, etc.
[0117] Although not shown, the computer device 1 may also include a power supply (such as a battery) to power various components. Preferably, the power supply can be logically connected to the at least one processor 13 through a power management device, thereby enabling functions such as charging management, discharging management, and power consumption management. The power supply may also include one or more DC or AC power supplies, recharging devices, power fault detection circuits, power converters or inverters, power status indicators, and other arbitrary components. The computer device 1 may also include various sensors, Bluetooth modules, Wi-Fi modules, etc., which will not be described in detail here.
[0118] Furthermore, the computer device 1 may also include a network interface. Optionally, the network interface may include a wired interface and / or a wireless interface (such as a Wi-Fi interface, a Bluetooth interface, etc.), which is typically used to establish communication connections between the computer device 1 and other computer devices.
[0119] Optionally, the computer device 1 may further include a user interface, which may be a display, an input unit (such as a keyboard), and optionally, a standard wired interface or a wireless interface. Optionally, in some embodiments, the display may be an LED display, a liquid crystal display, a touch-sensitive liquid crystal display, or an OLED (Organic Light-Emitting Diode) touchscreen, etc. The display may also be appropriately referred to as a screen or display unit, used to display information processed in the computer device 1 and to display a visual user interface.
[0120] It should be understood that the embodiments described are for illustrative purposes only and are not limited to this structure in the scope of the patent application.
[0121] It will be understood by those skilled in the art that Figure 3 The structure shown does not constitute a limitation on the computer device 1, and may include fewer or more components than shown, or combine certain components, or have different component arrangements.
[0122] Combination Figure 1 The memory 12 in the computer device 1 stores multiple instructions to implement a task execution method based on an annotation-driven mechanism, and the processor 13 can execute the multiple instructions to achieve: In the post-processing phase of the Bean Factory in the Spring container, the scan results are obtained by reading the Remote Procedure Call (RPC) scan package path configuration. The classpath scanner filters out the implementation classes marked with RPC service annotations from the scan results, parses the asynchronous task annotations on the RPC interface methods corresponding to the implementation classes, and generates global shared metadata based on the asynchronous task annotations. In the Bean post-processing phase of the Spring container, the original Beans of the instantiated RPC service are traversed, and a secondary proxy wrapping of the Bean is performed based on the original Beans and the global shared metadata. An independent interception proxy layer is added to the outer layer of the proxy generated by the original RPC framework to form a two-layer proxy structure, resulting in a secondary proxy Bean. In the initialization phase of the Spring container, the message queue infrastructure is dynamically registered based on the asynchronous task annotation in the global shared metadata. During the service operation phase, the RPC call request is intercepted by the method interceptor in the secondary proxy bean, and when the asynchronous task annotation is matched by querying the global shared meta information, the method parameters of the RPC call request are serialized into a message body carrying a type label, and the message body is sent through the message queue infrastructure. During the consumption phase, when the message body is received by the message listener in the message queue infrastructure, the method parameters are obtained by restoring the type label carried by the message body. The two-layer proxy structure is penetrated layer by layer to obtain the target business object with complete aspect enhancement. The target business object is used as the execution subject to execute the RPC business task carried by the message body through the reflection invocation mechanism.
[0123] Specifically, the processor 13's implementation method for the above instructions can be found in [reference needed]. Figure 1 The descriptions of the relevant steps in the corresponding embodiments are not repeated here.
[0124] It should be noted that all the data involved in this case was legally obtained.
[0125] If any AI models, software tools, or components not belonging to this company appear in the embodiments of this invention, they are merely illustrative examples and do not represent actual use. All user personal information involved in the embodiments of this invention has been obtained by an entity authorized (with the knowledge and consent) or fully authorized by all parties through various legal and compliant means. The collection, storage, use, processing, transmission, provision, and disclosure of the information, data, and signals involved all comply with relevant laws and regulations and do not violate public order and good morals.
[0126] Unless otherwise specified, the network models used in this embodiment are all general models with a general structure, and are trained and fine-tuned using data related to this embodiment, so as to be applicable to this embodiment.
[0127] In the several embodiments provided by this invention, it should be understood that the disclosed systems, apparatuses, and methods can be implemented in other ways. For example, the apparatus embodiments described above are merely illustrative; for instance, the division of modules is only a logical functional division, and other division methods may be used in actual implementation.
[0128] This invention can be used in a wide variety of general-purpose or special-purpose computer system environments or configurations. Examples include: personal computers, server computers, handheld or portable devices, tablet devices, multiprocessor systems, microprocessor-based systems, set-top boxes, programmable consumer electronics, network PCs, minicomputers, mainframe computers, and distributed computing environments including any of the above systems or devices. This invention can be described in the general context of computer-executable instructions, such as program modules, that are executed by a computer. Generally, program modules include routines, programs, objects, components, data structures, etc., that perform specific tasks or implement specific abstract data types. This invention can also be practiced in distributed computing environments where tasks are performed by remote processing devices connected via a communication network. In distributed computing environments, program modules can reside in local and remote computer storage media, including storage devices.
[0129] The modules described as separate components may or may not be physically separate. The components shown as modules may or may not be physical units; that is, they may be located in one place or distributed across multiple network units. Some or all of the modules can be selected to achieve the purpose of this embodiment according to actual needs.
[0130] Furthermore, the functional modules in the various embodiments of the present invention can be integrated into one processing unit, or each unit can exist physically separately, or two or more units can be integrated into one unit. The integrated unit can be implemented in hardware or in the form of hardware plus software functional modules.
[0131] It will be apparent to those skilled in the art that the present invention is not limited to the details of the exemplary embodiments described above, and that the present invention can be implemented in other specific forms without departing from the spirit or essential characteristics of the present invention.
[0132] Therefore, the embodiments should be considered exemplary and non-limiting in all respects, and the scope of the invention is defined by the appended claims rather than the foregoing description. Thus, all variations falling within the meaning and scope of equivalents of the claims are intended to be embraced within the invention. No appended diagram markings in the claims should be construed as limiting the scope of the claims.
[0133] Furthermore, it is clear that the word "comprising" does not exclude other units or steps, and the singular does not exclude the plural. Multiple units or devices described in this invention can also be implemented by a single unit or device through software or hardware. Terms such as "first," "second," etc., are used to indicate names and do not indicate any specific order.
[0134] Finally, it should be noted that the above embodiments are only used to illustrate the technical solutions of the present invention and are not intended to limit it. Although the present invention has been described in detail with reference to preferred embodiments, those skilled in the art should understand that modifications or equivalent substitutions can be made to the technical solutions of the present invention without departing from the spirit and scope of the technical solutions of the present invention.< / string> < / asynctasktagdto> < / string> < / string>
Claims
1. A task execution method based on an annotation-driven mechanism, characterized in that, The annotation-driven task execution method includes: In the post-processing phase of the Bean Factory in the Spring container, the scan results are obtained by reading the Remote Procedure Call (RPC) scan package path configuration. The classpath scanner filters out the implementation classes marked with RPC service annotations from the scan results, parses the asynchronous task annotations on the RPC interface methods corresponding to the implementation classes, and generates global shared metadata based on the asynchronous task annotations. In the Bean post-processing phase of the Spring container, the original Beans of the instantiated RPC service are traversed, and a secondary proxy wrapping of the Bean is performed based on the original Beans and the global shared metadata. An independent interception proxy layer is added to the outer layer of the proxy generated by the original RPC framework to form a two-layer proxy structure, resulting in a secondary proxy Bean. In the initialization phase of the Spring container, the message queue infrastructure is dynamically registered based on the asynchronous task annotation in the global shared metadata. During the service operation phase, the RPC call request is intercepted by the method interceptor in the secondary proxy bean, and when the asynchronous task annotation is matched by querying the global shared meta information, the method parameters of the RPC call request are serialized into a message body carrying a type label, and the message body is sent through the message queue infrastructure. During the consumption phase, when the message body is received by the message listener in the message queue infrastructure, the method parameters are obtained by restoring the type label carried by the message body. The two-layer proxy structure is penetrated layer by layer to obtain the target business object with complete aspect enhancement. The target business object is used as the execution subject to execute the RPC business task carried by the message body through the reflection invocation mechanism.
2. The task execution method based on annotation-driven mechanism as described in claim 1, characterized in that, The step of generating globally shared metadata based on the asynchronous task annotation includes: Extract annotation metadata from each asynchronous task annotation; The annotation meta-information of each asynchronous task annotation is aggregated according to the Bean name and stored in the shared meta-information mapping to obtain the global shared meta-information.
3. The task execution method based on annotation-driven mechanism as described in claim 1, characterized in that, The step of performing secondary proxy wrapping of the Bean based on the original Bean and the global shared metadata, adding an independent interception proxy layer to the outer layer of the proxy generated by the original RPC framework to form a two-layer proxy structure, yields the secondary proxy Bean, including: Based on the original bean name of the original bean, query the global shared meta information to filter out the target original bean that contains the asynchronous task annotation; The target original Bean is secondary proxied and wrapped using a proxy factory, and the method interceptor of the independent interception proxy layer is injected. Obtain the secondary proxy object generated by the proxy factory as the secondary proxy bean.
4. The task execution method based on annotation-driven mechanism as described in claim 1, characterized in that, The process of dynamically registering message queue infrastructure based on asynchronous task annotations in the global shared metadata includes: Iterate through all metadata data objects in the global shared metadata, and perform queue registration and listener registration for each asynchronous method encountered, to obtain each queue and each listener; By combining each queue and each listener, the message queue infrastructure is obtained.
5. The task execution method based on annotation-driven mechanism as described in claim 1, characterized in that, The step of serializing the method parameters of the RPC call request into a message body carrying a type label includes: The method parameters are serialized to obtain serialized parameters; The serialization parameters are embedded into parameter type tags used for deserialization and restoration of parameters on the consumer side to assemble the message body.
6. The task execution method based on annotation-driven mechanism as described in claim 1, characterized in that, The method further includes: When the query of the global shared metadata determines that the asynchronous task annotation is not matched, the original Bean is passed through for invocation.
7. The task execution method based on annotation-driven mechanism as described in claim 1, characterized in that, The execution of the RPC business task carried in the message body via reflection invocation mechanism includes: Based on the target method identifier carried in the message body and the method parameters obtained by reconstruction, the corresponding RPC business task is executed on the target business object through the reflection invocation mechanism.
8. A task execution device based on an annotation-driven mechanism, characterized in that, The annotation-driven task execution device includes: The generation unit is used in the post-processing stage of the Bean Factory in the Spring container to read the Remote Procedure Call (RPC) scan package path configuration to obtain the scan results, filter out the implementation classes marked with RPC service annotations from the scan results through the classpath scanner, parse the asynchronous task annotations on the RPC interface methods corresponding to the implementation classes, and generate globally shared metadata based on the asynchronous task annotations. The execution unit is used to traverse the original beans of the instantiated RPC service during the Bean post-processing phase of the Spring container, and perform secondary proxy wrapping of the beans according to the original beans and the global shared meta information. An independent interception proxy layer is added to the outer layer of the proxy generated by the original RPC framework to form a two-layer proxy structure and obtain the secondary proxy bean. The registration unit is used to dynamically register the message queue infrastructure based on the asynchronous task annotation in the global shared meta-information during the initialization phase of the Spring container. The interception unit is used to intercept RPC call requests through the method interceptor in the secondary proxy bean during the service operation phase, and when the asynchronous task annotation is determined to be matched by querying the global shared meta information, serialize the method parameters of the RPC call request into a message body carrying a type label, and send the message body through the message queue infrastructure. The execution unit is also used in the consumption phase to, when the message body is received by the message listener in the message queue infrastructure, restore the method parameters based on the type label carried by the message body, penetrate the two-layer proxy structure layer by layer to obtain the target business object with complete aspect enhancement, and use the target business object as the execution subject to execute the RPC business task carried by the message body through the reflection call mechanism.
9. A computer device, characterized in that, The computer device includes: A memory for storing at least one instruction; and a processor for executing the instructions stored in the memory to implement the annotation-driven task execution method as described in any one of claims 1 to 7.
10. A computer-readable storage medium, characterized in that: The computer-readable storage medium stores at least one instruction, which is executed by a processor in a computer device to implement the annotation-driven task execution method as described in any one of claims 1 to 7.
