How can I create multiple servers with Java RMI? - java

I need:
A client, which communicates with the front-end, which communicates with 3 file servers.
How should I go about doing this? It needs to use RMI as distributed systems.
I also need to monitor all three file servers.
From what I understand, I need to establish an RMI registry, but how do I establish three concurrent servers within one registry?

Okay, so am I right in thinking i'd have the following: A server interface, a server implementation, and a master server which creates the three servers (with unique names) and finally a client?
The 'master server' needs to create a Registry on its own localhost, bind itself to the Registry so the slave servers can find it, and export a remote interface that lets the servers register themselves with it.
The master server must do the binding to this Registry on behalf of the slaves, as you can't bind to a remote Registry. But in fact the slaves don't need to be bound to the Registry at all, only registered with the master.
The master needs to export a second remote interface that provides the API to the client, which provides the upload API and whose implementation performs the balancing act. I would keep this interface separate from the interface used by the slaves, both for security reasons and for simplicity: you don't need clients trying to be slaves, or worrying about what the slave-relevant methods in the remote interface are.
All these servers and registries can run on port 1099.
The slaves are presumably multiple instances of the same service, so they all use a common remote interface. This interface provides the upload-to-slave API, and it also needs to allow each slave to provide the knowledge about how full each slave is, possibly as a return value from the upload method, or else as a query method.
Quick sketch:
public interface UploadMaster extends Remote
{
void upload(String name, byte[] contents) throws IOException, RemoteException;
}
public interface LoadBalancingMaster extends Remote
{
void register(Slave slave) throws RemoteException;
void unregister(Slave slave) throws RemoteException;
}
public interface Slave extends Remote
{
/** #return the number of files now uploaded to this slave. */
int upload(String name, byte[] contents) throws IOException, RemoteException;
int getFileCount() throws RemoteException;
}
I hope this is homework. RMI is a poor choice for file transfer, as it bundles up the entire argument list into memory at both ends, rather than providing a streaming interface.

Related

Understanding java RMI exportObject method

I'm very new to RMI and I just decided to give it a try. I got confused by the exportObject(Object, int) method. The documentation says:
Exports the remote object to make it available to receive incoming
calls, using the particular supplied port. The object is exported with
a server socket created using the RMISocketFactory class.
Consider the following simple example:
public interface Client extends Remote {
void clientMethod() throws RemoteException;
}
public class ClientImpl implements Client {
public clientMethod() throws RemoteException {
System.out.println("clientMethod invoked");
}
}
Client stub = (Client) UnicastRemoteObject
.exportObject(new ClientImpl(), 56789); //<------ HERE
So we create a stub and will transfer it to another VM either manually or through RmiRegistry, doesn't matter here.
I'm confused by "[...] the object is exported with a server socket [...]"
What do they mean by that?
A ServerSocket is created to listen for incoming connections at the port you specified when exporting. This port can be shared between multiple remote objects.
The statement about the RMISocketFactory is incorrect. Where did you read that? This class has been obsolete since 1998.
The stub contains the server's hostname or IP address and port number, and some internal data to identify the remote object it belongs to.
TCP connections between the stub and the remote object are created on demand when you call remote methods, via a connection pool.
So, when we transfer the stub to another VM (VM 0), the stub will hold a socket connection to the VM (VM 2) it was originally created on.
No, see above.
The VM 2 in turn will maintain a server socket to accept incoming method invocations.
Correct.

Persisting data in TCP server while client channel is connected

I'm building a TCP Server using Netty.
Is there any way to persist the connected client's session data while its channel exists?
for example, when a client connect to the server, I need to create its class instance and reuse in different ways when he send messages.
something like the code below:
// this is called when the client connect to the server
public void channelActive(final ChannelHandlerContext ctx) {
ctx.pipeline().get(SslHandler.class).handshakeFuture().addListener(
new GenericFutureListener<Future<Channel>>() {
public void operationComplete(Future<Channel> future) throws Exception {
// I need to create the class instance when the
// client connects to the server
ClientData clientData = new ClientData(ctx.channel());
channels.add(ctx.channel());
}
}
);
}
// this is called when the server receives a message from the connected client
public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
if("update".equals(msg)){
// then I need the retrieve the data created
// in the ChannelActive method.
clientData().update();
}
}
While browsing for solutions, I found a few examples where the developer used a cache service (like memcache or redis) to store and retrieve the data related to the connected client.
But I wish to solve this without depending on a external process.
Is there any way to achieve this? Any advice on the subject would be appreciated.
Thank you
You should use AttributeMap.attr(AttributeKey key), which is inherited by ChannelHandlerContext:
Storing stateful information
AttributeMap.attr(AttributeKey) allow you to store and access stateful information that is related with a handler and its context. Please refer to ChannelHandler to learn various recommended ways to manage stateful information. [1]
[1][http://netty.io/4.0/api/io/netty/channel/ChannelHandlerContext.html]

Pass Remote object in method to RMI server?

I have an RMI client that connects to some RMI server just to let it know it can use this new client.
Can I pass directly some Remote object so that:
serverRemoteObject.registerClient(theClientRemoteObjectTheServerShouldUse);
will actually give the server some object he can use without connecting to my client?
The following question says it is possible, but no real example was given:
Is it possible to use RMI bidirectional between two classes?
Andrew
Yes, you can. This is how exactly callbacks work in case of RMI. You send across an object to the server and when the server invokes a method on your object, it would be executed in the "client" JVM as opposed to on the server. Look into UnicastRemoteObject.export method for export any object which implements the Remote interface as a remote object which can be passed to your server.
interface UpdateListener extends Remote {
public void handleUpdate(Object update) throws RemoteException;
}
class UpdateListenerImpl implements UpdateListener {
public void handleUpdate(Object update) throws RemoteException {
// do something
}
}
//somewhere in your client code
final UpdateListener listener = new UpdateListenerImpl();
UnicastRemoteObject.export(listener);

Migrating an application to a service mode [java/groovy]

I've got an application written in groovy. It takes some cmd args and returns previously formatted response. As system grew, it appeared that it is required to run this app extremely frequently (like 80 times in 5 mins) which leads to certain performance issues. In particular it creates all its objects over and over again which leads to filling up to 60MB RAM in one run (can be easily calculated how severely ROM/swap is used).
I want to migrate it to a service running mode which will simply take certain params and return formatted output. But:
App is always triggered by a bat/sh script (this can't be changed)
Both script and app are on the same host server
So, I'm wondering how it would be better to perform the communication of a script and a service?
P.S.: Sorry that I didn't mention, it's a standalone app, it will never use a server or anything like that as it appears to be redundant. Solution should be as simple as possible and extremely lightweight.
Example: The simplest thing I can think of by now is never to migrate it (I know it's contradictory ;)) and simply introduce a DB where all thee result will be stored and an app will have it's own schedule of when to trigger. Whenever it is triggered with any params, it should simply search the latest result in DB and return it. Easy, light, fast, and working. :)
For enterprise environments I would suggest a JavaEE application with EJB running in an application server. For your requirements this might be an overkill. A simple solution can be:
Service: Implement a RMI server with a local RMI registry. Calculations will be done here.
Script: Connect to the RMI server, invoke a method at the RMI server and display the result.
RMI Server
public class RmiServer extends UnicastRemoteObject implements RmiInterface
{
private static final long serialVersionUID = 1L;
public RmiServer() throws RemoteException
{
super();
}
public String random() throws RemoteException
{
return "Helo World! "+(new Random()).nextInt(100);
}
public static void main(String[] args) throws RemoteException, MalformedURLException
{
LocateRegistry.createRegistry(Registry.REGISTRY_PORT);
Naming.rebind("myServer", new RmiServer());
}
}
RMI Client
RmiInterface server = (RmiInterface)Naming.lookup("//127.0.0.1/myServer");
System.out.println(server.random());
RMI Interface
public interface RmiInterface extends Remote
{
public String random() throws RemoteException;
}

RMI - create thread on server to serve client

I'm developing a application using rmi which allow client to login, perform some task and logout. I know that each client is considered as one thread when it call a method on server, however, all clients' threads call to the same object created on server. So now, I want to for each client login successfully, a new thread is created (and a new object, which is used by only one client, is binded, too), a thread terminates when client logout. Hence, each client has its own server's object to work with.
Thank you very much.
Cheers
I know that each client is considered
as one thread when it call a method on
server
That's not correct. The relationship between clients and server threads is undefined in RMI.
In any case you don't need a thread per client. You need a remote object per client. This is a job for the Session pattern:
public interface Login extends Remote
{
Session login(String credentials) throws RemoteException;
}
public interface Session extends Remote
{
// Your API here
}
Have your Login implementation object return a new Session implementation object for every client.

Categories

Resources