Ir ao conteúdo

Java RMI – Introdução e Exemplo

Boa noite,

Java RMI (Remote Method Invocation), é um mecanismo que permite ao usuário, criar aplicações distribuídas utilizando Java. Sem ter muitas preocupações com Protocolo, sockets entre outros. Mas como ele funciona? Bom toda a mágica é feita pelo próprio RMI. O mesmo possui um servidor chamado RMIREGISTRY, onde o seu Servidor se conecta e diz que está ali. A partir desse momento os Clientes conseguem invocar o servidor.

Um exemplo de um Servidor de Veiculo onde os Clientes podem pesquisar e adicionar novos Veículos.

Interface Servidor:
[code lang=”java”]
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.List;

public interface MethosInterfaces extends Remote {

public List search(String field, String value) throws RemoteException;
public void add(Vehicle v) throws RemoteException;
}
[/code]

Os métodos nessa interface serão implementados por nosso servidor, essa interface extend Remote que é uma Classe necessária para fazer o RMI funcionar. Se sua interface não extende-la não irá funcionar. Todos os métodos devem possuir o tratamento de exceção, para garantir o que vai acontecer caso o servidor não seja encontrado.

Servidor:
[code lang=”java”]
public class ServerAn implements MethosInterfaces {
[/code]

Classe extende nossa interface e implementa os métodos (não irei mostra-los aqui).

Para criar o servidor utilizei o seguinte:

[code lang=”java”]
public static void main(String[] args) {
try {
ServerAn server = new ServerAn();
MethosInterfaces stub = (MethosInterfaces) UnicastRemoteObject.exportObject(server, 0);
Registry registry = LocateRegistry.getRegistry();
registry.bind(“Server”, stub);
System.out.println(“Servider running”);
} catch (Exception ex) {
ex.printStackTrace();
}
}
[/code]

Bom no main criamos um novo ServerAn(), exportamos o nosso Servidor, registramos com o bind o nosso Servidor.

Cliente Enviador:
[code lang=”java”]
public class ClientSender {

public static void main(String[] args) {
try {
Registry registry = LocateRegistry.getRegistry(“localhost”);
MethosInterfaces stub = (MethosInterfaces) registry.lookup(“Server”);
System.out.println(“Sending new Vehicle to server”);
stub.add(new Vehicle(“Matheus2”, 5000, “Caminhão”, “”, 2008));
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
[/code]

Basicamente, procuramos o RMIREGISTRY em “localhost” e procuramos pelo nosso servidor nomeado “Server”, com referencia para o mesmo adicionamos um novo Veículo. Para procurar é a mesma coisa porém receberemos uma Lista de veículos ao invés de não receber nada.

Para o objeto poder ser transmitido ele deve ser “serializable”.

Java RMI – Anúncios de Carros (Exemplo)

Lembrando que, o rmiregistry procura no seu Java PATH e no diretório que o mesmo foi executado pelas interfaces. Então neste exemplo, para simplicidade, acesse o diretório com os códigos fontes, compile-os execute o RMIREGISTRY no mesmo. E em seguida o Servidor, após isso em outro prompt execute o(s) Clientes. O nome do programa é RMIREGISTRY, execute-o com seu nome.

Espero que seja util,
Matheus

PS: Java ME não vem com o RMI

Referencias:
http://infolab.stanford.edu/CHAIMS/Doc/Details/Protocols/rmi/rmi_description.html
http://www.oracle.com/technetwork/java/javase/tech/index-jsp-136424.html

Publicado emjava

6 Comentários

  1. […] Enviado por Matheus Bratfisch (matheusbratΘgmail·com): “Java RMI, Remote Method Invocation. Para fazer aplicativos distribuídos praticamente de forma transparente em Java. Nesta publicação é demonstrado alguns conceitos básicos da utilização do mesmo, de maneira prática, junto a um exemplo.” [referência: matbra.com] […]

  2. Einfach admiral-casinos1.com in Ihrem Browser öffnen Auf Anfrage bietet dieses Unternehmen Einzahlungslimits, Verlustobergrenzen und „Abkühlfristen“ an, damit Sie verantwortungsvoll spielen können. Legen Sie Einzahlungs- und
    Verlustlimits in den Einstellungen Ihres Spielkontos fest, bevor
    Sie Spielautomaten oder Tische spielen. Studieren Sie, wie Sie spielen, und finden Sie
    die besten Möglichkeiten, sich zu engagieren, um das Beste aus diesen Vorteilen herauszuholen.
    Elektronisches Roulette und automatisierte
    Varianten bewegen sich schnell, aber Live-Dealer-Spiele
    ermöglichen es Ihnen, bequem von zu Hause aus zu spielen. Sie können viele verschiedene Arten von Blackjack, Roulette,
    Baccarat und Poker spielen und die Grafiken und Soundeffekte sind realistisch.
    Die Leute spielen immer noch gerne Spiele wie Lucky Lady’s Charm™, Reel King™ und Eye of Horus auf der Admiral-Plattform.
    Im Admiral Casino Online sind Spielautomaten die Hauptattraktion, die die
    Spieler immer wieder zurückkommen lässt, egal ob sie neu im Spiel sind
    oder schon lange spielen. Progressive Jackpots bieten lebensverändernde Gewinne in €,
    während Bonusrunden und Freispiele die Spannung aufrechterhalten.
    Wenn Sie Ihr Konto so sicher wie möglich halten möchten, insbesondere
    auf öffentlichen oder gemeinsam genutzten Geräten, stellen Sie sicher, dass Sie
    sich am Ende jeder Sitzung abmelden. Alle Informationen deutscher Spieler, die sie während des Anmeldevorgangs eingeben, werden verschlüsselt, um sie sicher
    aufzubewahren. Bevor Sie vertrauliche Informationen eingeben,
    stellen Sie immer sicher, dass Sie über https verbunden sind,
    und überprüfen Sie die Homepage-Adresse erneut. Wenn Sie Ihre Registrierungsinformationen bereithalten, wird der Einstiegsprozess beschleunigt.

    References:
    https://online-spielhallen.de/drip-casino-bewertung-ein-detaillierter-blick-auf-das-online-glucksspielerlebnis/

  3. Der Rückgang der Beliebtheit der Riviera wurde zum Teil durch
    den Rückgang des Fußgängerverkehrs in der Nähe verursacht.
    Unter den Bedingungen der von Starwood ausgehandelten Vereinbarung würden gesicherte
    Kreditgeber ein neues Darlehen von $50 Millionen plus 80% der neuen Aktie erhalten. Das Geschäft entstand 1993 als
    Riviera Holdings Corp. im Besitz der bisherigen gesicherten Gläubiger aus dem Konkurs.

    Das erschwingliche 2-Sterne-Days Inn By Wyndham Las Vegas Airport Near The Strip verfügt über 2 Casinos und liegt 2 km weit weg
    vom Mandalay Bay Resort and Casino. Bali Hai Golfklub befindet sich circa 5 Kilometer von dem
    komfortable 2-Sterne-Highland Inn Las Vegas entfernt und ist einen Besuch
    wert. Das 4-Sterne-Orleans Hotel And Casino Las Vegas bietet eine großartige Lage in 2 km Entfernung von Wellness-Einrichtungen wie dem MGM Grand Hotel und bietet allen Gästen ein Restaurant.

    Das 4-Sterne-Jet Luxury At The Signature Condo Hotel Las Vegas mit einem beheizten Swimmingpool liegt direkt neben dem Planet Hollywood
    Resort and Casino und ist nur 12 Minuten zu Fuß vom
    The… Das Thunderbird Boutique Hotel Las Vegas beeindruckt
    die Gäste mit einem Swimmingpool und liegt unter anderem
    im Viertel Downtown Las Vegas – Fremont Street. Das 3-Sterne-Hotel
    Excalibur Las Vegas befindet sich weniger als 7 Minuten zu Fuß
    von der Bodies The Exhibition entfernt und bietet seinen Gästen einen Gepäckraum und ein Restaurant.

    References:
    https://online-spielhallen.de/playfina-casino-freispiele-ihr-umfassender-leitfaden/

  4. Our Service may contain links to other sites that are not
    operated by us. We collect information that your browser
    sends whenever you visit our Service (“Log Data”). Our specialists start by examining the certificate and also their experience, to
    make sure that those who follow our guidance are actually protected.
    Experience the forefront of slot entertainment, access exclusive rewards, and spin your way to major triumphs.
    At Australianvu.com, we are dedicated to enhancing your gameplay with unparalleled promotions and bonuses designed to
    boost your wins.
    The first step assumes to get an account at a qualified online casino at which all of your games will be obtainable.
    If you have got a good knowledge of casinos
    online Australia, that’s the moment to order the real money type.
    Due to all of our reviews being unquestionably clear, players will find immediately the things you take and can easily
    make a commonsense choice on Australian casinos online and if
    you wish to join under the offered conditions.
    Those casinos online Australia all of us support are always accessible on cell phones and besides some of them often provoke gamblers to utilize smartphones and tablets granting additional
    bonuses and exceptional promotions.
    Slot fans are certainly the most significant segment of online
    gamers who really pay a lot of money on gambling. Countless number of players are fond of online slots
    by uncomplicated gaming which usually is not going to demand any
    sort of practice nor methods. Only to make inexperienced online
    gamblers a bit more aware of the process of participating
    in casino online Australia, it is necessary to point out some of the most significant parts
    of the activity. Welcome to Australianvu.com, your ultimate destination for exceptional online casino action!

    References:
    https://blackcoin.co/ripper-casino-bonus-codes-november-2025/

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *