写一个用Java8将共通工具类服务化以及调用该服务的例子
时间: 2024-05-13 11:13:33 浏览: 11
假设我们有一个共通工具类StringUtil,其中有一个方法将字符串反转:
```java
public class StringUtil {
public static String reverse(String str) {
return new StringBuilder(str).reverse().toString();
}
}
```
现在我们想要将这个工具类服务化,可以使用Java8中的函数式接口来实现:
```java
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface StringUtilService extends Remote {
String reverse(String str) throws RemoteException;
}
```
接下来我们需要实现这个接口:
```java
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class StringUtilServiceImpl extends UnicastRemoteObject implements StringUtilService {
protected StringUtilServiceImpl() throws RemoteException {
super();
}
@Override
public String reverse(String str) throws RemoteException {
return StringUtil.reverse(str);
}
}
```
现在我们已经将StringUtil服务化了,接下来我们可以通过RMI调用这个服务:
```java
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Client {
public static void main(String[] args) throws Exception {
Registry registry = LocateRegistry.getRegistry("localhost", 1099);
StringUtilService service = (StringUtilService) registry.lookup("StringUtilService");
String reversedStr = service.reverse("hello world");
System.out.println(reversedStr);
}
}
```
最后我们需要将服务注册到RMI Registry中:
```java
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Server {
public static void main(String[] args) throws Exception {
Registry registry = LocateRegistry.createRegistry(1099);
registry.bind("StringUtilService", new StringUtilServiceImpl());
}
}
```
现在我们就成功地将StringUtil服务化并调用了该服务。