跨JVM同步方法 [英] Synchronizing a Method Across JVM's

查看:300
本文介绍了跨JVM同步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何跨JVM同步方法?

How does one go about synchronizing a method across JVM's?

我的示例是一个Web应用程序,该应用程序限制一个用户名不能多次登录(换句话说,第一个用户可以登录,但是如果另一个用户使用相同的用户名登录,他将被拒绝).

My example is a web application that restricts a user name from being logged in more than once (in other words, the first user can log on, but if another user signs on with the same user name, he gets rejected).

该Web应用程序部署在多个服务器上,因此有多个JVM,并且用户可能会尝试使用不同的服务器进行登录,具体取决于负载平衡器.

The web application is deployed across multiple servers, so there are multiple JVM's, and users can be attempting to sign on using different servers, depending on the load balancer.

这是该方法的外观

public synchronized static SessionData logonSync(String userName, String password) throws Exception 
{
    int count = DB.count("sessions", "WHERE user_name=?", userName);
    if (count > 0)
    {
       throw new Exception("logon.error.loginAlreadyUsed");
    }                   

    return logon(userName, password);
}

由于采用了同步方法,因此它可以在1个应用服务器上正常运行,但是可以跨多个JVM?两个用户可能试图同时登录不同的Web应用程序.我该如何预防?

It works correctly on 1 app server because of the synchronized method, but across multiple JVM's? Two users could be attempting to log in on different web apps at the same time. How would I prevent this?

*编辑* 如果您的解决方案想要利用某些事务性缓存方法,则该应用程序也将使用Memcached.

* EDIT * The app uses Memcached too, if your solution wants to take advantage of some transactional cache methods.

推荐答案

您问过有关跨JVM同步方法的问题.这就需要一个处理分布式进程的库.有很多选择,这里只是几个:

You asked about synchronizing methods across JVMs. That requires a library that handles distributed processes. There are many options, here are just a few:

  1. Terracotta -支持将某些字段配置为在JVM之间共享",因此您可以使用标准的JVM锁定,像synced关键字一样,它可以在多个JVM上使用.
  2. JGroups -Jgroups是用于分布式应用程序的工具包.锁定是它提供的功能之一.这是他们的文档
  3. 中的示例
  1. Terracotta - Supports configuring certain fields as 'shared' across JVMs, so you can use standard JVM locking, like the synchronized keyword, and it will work on multiple JVMs.
  2. JGroups - Jgroups is a toolkit for distributed applications. Locking is one of the features it offers. Here is an example from their documentation

不管使用什么库,设置分布式锁定都不是一件容易的事.如果需要的话,很好,但是对于您的示例,这似乎有点过头了.其他选项:

Setting up distributed locking is never easy, regardless of what library you use. If you need it, fine, but for your example this seems like overkill. Other options:

  • 在数据库中添加唯一性约束,让其强制执行唯一性.这可能会对数据库的性能产生影响,因此它实际上取决于您希望获得多少流量.
  • 让负载均衡器使用用户名(或用户名的哈希)作为用于将请求分配给Web服务器的密钥.这样可以确保来自同一用户名的请求每次都将到达同一Web服务器-无需分布式锁,只需使用常规锁即可.

这篇关于跨JVM同步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆