基於JMS訊息中介軟體的分布式系統初探究(二),jms訊息中介軟體探究

來源:互聯網
上載者:User

基於JMS訊息中介軟體的分布式系統初探究(二),jms訊息中介軟體探究

在上一篇文章中,我們解決了子系統之間的通訊問題,並跑起來了一個模型項目。這裡我們要詳細實現服務端程式。

我們在服務端運行Spring,利用Spring的IoC容器來管理所有的Service組件,然後根據接收到的JMS訊息通過反射動態調用Service方法。

首先要先設計一下協議:

public class MessageProtocol implements Serializable {    /**     * 要調用的介面全限定名     */    private String interfaceName;    /**     * 要調用的方法名     */    private String methodName;    /**     * 方法參數列表     */    private List<Object> argList;    // setter and setters ...}

由上協議類可以看出,我們是通過介面名、方法名和參數列表來定位服務端組件的。假如在服務端我們有一個AccountService介面的實作類別DefaultAccountService:

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

我們想要在用戶端調用其registerMember()方法,那麼就應該這樣封裝MessageProtocol類:

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

然後將這個對象以ObjectMessagepayload的格式通過JMS發送給服務端,服務端要做的工作是:

由於Java的反射機制中調用Class#getDeclaredMethods()方法開銷比較大,所以我們應該緩衝得到的Method對象。思想是,當用戶端第一次請求該方法時,先調用getDeclaredMethods()方法,將返回的結果儲存到一個Map<String, List<Method> >資料結構中,即:

    /**     * K: 介面的全限定名     * <p> V: 這個介面實作類別的所有{@code Method}對象     */    public static Map<String, List<Method>> methodCache = new HashMap<>();

然後,當下一次用戶端要請求這個組件的方法時,直接從methodCache中尋找而不是調用getDeclaredMethods()方法,這樣能極大提高運行效率。
訊息處理方法如下:

public Object onMessage(MessageProtocol protocol) {        System.out.println("message received");        // 取出請求資訊        // 介面名        String interfaceName = protocol.getInterfaceName();        // 參數列表        List<Object> argList = protocol.getArgList();        // 方法名        String methodName = protocol.getMethodName();        Object returnVal = null;        try {            Class clazz = Class.forName(interfaceName);            Object service = BeanUtil.getBeanByInterface(clazz);            // 反射調用            returnVal = BeanUtil.invokeMethod(clazz, service, methodName, argList.toArray());        } catch (// ... ...) {           // ... ...        }        return returnVal;    }

BeanUtil工具類的完整實現如下:

public class BeanUtil {    private BeanUtil() {    }    /**     * 通過反射調用商務邏輯方法     * @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;    }    /**     * 通過介面Class對象,從Spring容器中得到對應的實現組件     */    public static <T> T getBeanByInterface(Class<T> clazz) {        T result = null;        Map<String, T> map = ContextHolder.ctx.getBeansOfType(clazz);        // 返回第一個bean        Set<Map.Entry<String, T>> set = map.entrySet();        for (Map.Entry<String, T> entry : set) {            result = entry.getValue();            break;        }        cacheMethod(clazz);        return result;    }    /**     * 如果是第一次調用,緩衝Class的Method對象     * @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);    }    /**     * 從Cache中得到Method對象     */    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();    }}

至此,一個完整可用的分布式網站後端就能夠運行起來了。當然這隻是一個粗獷的實現,還有很多可以進行效能最佳化的地方。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.