Research on the Distributed System Based on JMS Message Middleware (2); Research on jms Message Middleware

Source: Internet
Author: User

Research on the Distributed System Based on JMS Message Middleware (2); Research on jms Message Middleware

In the previous article, we solved the communication problem between subsystems and ran a model project. Here we need to implement the server program in detail.

We run Spring on the server, use the IoC container of Spring to manage all the Service components, and then follow the received JMS messageCall the Service method dynamically through reflection.

First, design the Protocol:

Public class MessageProtocol implements Serializable {/*** name of the interface to be called */private String interfaceName;/*** name of the method to be called */private String methodName; /*** method parameter List */private List <Object> argList; // setter and setters ...}

We can see from the above Protocol class that we are usingInterface Name, method name, and parameter listTo locate the server component. Assume that we haveAccountServiceInterface implementation classDefaultAccountService:

public interface AccountService {    void registerMember(MemberDto dto);    void sayHello(String name);}

We want to callregisterMember()Method, then it should be encapsulated in this wayMessageProtocolClass:

    interfaceName = "com.fh.common.service.AccountService";    methodName = "registerMember";    argList = Arrays.asList(new MemberDto());

Then, set the objectObjectMessageThe payload format is sent to the server through JMS. The server must do the following:

Because Java reflection mechanism callsClass#getDeclaredMethods()Method overhead is relatively large, so we should cacheMethodObject. The idea is that when the client first requests this method, it first callsgetDeclaredMethods()Method To save the returned results toMap<String, List<Method> >In the data structure, that is:

/*** K: Fully Qualified interface name * <p> V: All the {@ code Method} objects of this interface implementation class */public static Map <String, list <Method> methodCache = new HashMap <> ();

Then, when the client requests the method of this componentmethodCache, Rather than callinggetDeclaredMethods()To greatly improve the running efficiency.
The message processing method is as follows:

Public Object onMessage (MessageProtocol protocol) {System. out. println ("message received ed"); // retrieve request information // Interface Name String interfaceName = protocol. getInterfaceName (); // List of parameters <Object> argList = protocol. getArgList (); // method name String methodName = protocol. getMethodName (); Object returnVal = null; try {Class clazz = Class. forName (interfaceName); Object service = BeanUtil. getBeanByInterface (clazz); // reflection call returnVal = BeanUtil. invokeMethod (clazz, service, methodName, argList. toArray ();} catch (//......) {//......} return returnVal ;}

BeanUtilThe complete implementation of the tool class is as follows:

Public class BeanUtil {private BeanUtil () {}/*** call the business logic method through reflection * @ param clazz * @ param methodName * @ param <T> */public static <T> Object invokeMethod (Class <T> clazz, object component, String methodName, Object [] args) throws NoSuchMethodException, NoSuchClassException, InvocationFailedException {Method method = getMethodInCache (clazz. getName (), methodName); Object returnValue = null; try {returnValue = method. invoke (component, args);} catch (IllegalAccessException e) {throw new InvocationFailedException ("invoke" + methodName + "failed");} catch (InvocationTargetException e) {throw new InvocationFailedException ("invoke" + methodName + "failed");} return returnValue;}/*** interface Class object, obtain the corresponding implementation component */public static <T> T getBeanByInterface (Class <T> clazz) {T result = null; Map <String, t> map = ContextHolder. ctx. getBeansOfType (clazz); // return the first bean Set <Map. entry <String, T> set = map. entrySet (); for (Map. entry <String, T> entry: set) {result = entry. getValue (); break;} cacheMethod (clazz); return result;}/*** if this is the first call, cache Class Method object * @ param clazz * @ param <T> */private static <T> void cacheMethod (Class <T> clazz) {if (false = isAlreadyCached (clazz. getName () {Method [] methods = clazz. getDeclaredMethods (); ContextHolder. methodCache. put (clazz. getName (), Arrays. asList (methods);} private static boolean isAlreadyCached (String className) {return ContextHolder. methodCache. containsKey (className);}/*** obtain the Method object from the Cache */private static Method getMethodInCache (String className, String methodName) throws NoSuchClassException, noSuchMethodException {List <Method> methodList = ContextHolder. methodCache. get (className); if (null = methodList) {throw new NoSuchClassException (className);} Optional <Method> optMethod = methodList. stream (). filter (meth)-> {return meth. getName (). equals (methodName );}). findAny (); if (false = optMethod. isPresent () {throw new NoSuchMethodException (methodName);} return optMethod. get ();}}

So far, a complete and available distributed website backend can run. Of course, this is just a rough implementation, and there are many other aspects that can be used for performance optimization.

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.