動(dòng)態(tài)代理例子
使用動(dòng)態(tài)代理的步驟很簡(jiǎn)單, 可以概括為如下兩步:
- 實(shí)現(xiàn) InvocationHandler 接口, 并在 invoke 中調(diào)用真實(shí)對(duì)象的對(duì)應(yīng)方法.
- 通過(guò) Proxy.newProxyInstance 靜態(tài)方法獲取一個(gè)代理對(duì)象.
為什么需要使用動(dòng)態(tài)代理嗅定,不使用靜態(tài)代理
- 動(dòng)態(tài)代理具有更強(qiáng)的靈活性, 因?yàn)樗挥迷谖覀冊(cè)O(shè)計(jì)實(shí)現(xiàn)的時(shí)候就指定某一個(gè)代理類來(lái)代理哪一個(gè)被代理對(duì)象, 我們可以把這種指定延遲到程序運(yùn)行時(shí)由JVM來(lái)實(shí)現(xiàn).
- 動(dòng)態(tài)代理更為統(tǒng)一與簡(jiǎn)潔脐帝。
在很多方法都需要代理的時(shí)候,動(dòng)態(tài)代理更加快千绪。
比如給每個(gè)方法加日志,靜態(tài)代理需要修改每一個(gè)方法儡炼,但是動(dòng)態(tài)代理只要修改幾行代碼芒帕,直接就能搞定
接口
public interface HelloService {
String sayHi(String name);
}
實(shí)現(xiàn)類
public class HelloServiceImpl implements HelloService {
public String sayHi(String name) {
return "Hi, " + name;
}
}
服務(wù)中心代碼
public interface Server {
public void stop();
public void start() throws IOException;
public void register(Class serviceInterface, Class impl);
public boolean isRunning();
public int getPort();
}
public class ServiceCenter implements Server {
private static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
private static final HashMap<String, Class> serviceRegistry = new HashMap<String, Class>();
private static boolean isRunning = false;
private static int port;
public ServiceCenter(int port) {
this.port = port;
}
public void stop() {
isRunning = false;
executor.shutdown();
}
public void start() throws IOException {
ServerSocket server = new ServerSocket();
server.bind(new InetSocketAddress(port));
System.out.println("start server");
try {
while (true) {
// 1.監(jiān)聽(tīng)客戶端的TCP連接,接到TCP連接后將其封裝成task鞍历,由線程池執(zhí)行
executor.execute(new ServiceTask(server.accept()));
}
} finally {
server.close();
}
}
public void register(Class serviceInterface, Class impl) {
serviceRegistry.put(serviceInterface.getName(), impl);
}
public boolean isRunning() {
return isRunning;
}
public int getPort() {
return port;
}
private static class ServiceTask implements Runnable {
Socket clent = null;
public ServiceTask(Socket client) {
this.clent = client;
}
public void run() {
ObjectInputStream input = null;
ObjectOutputStream output = null;
try {
// 2.將客戶端發(fā)送的碼流反序列化成對(duì)象舵抹,反射調(diào)用服務(wù)實(shí)現(xiàn)者,獲取執(zhí)行結(jié)果
input = new ObjectInputStream(clent.getInputStream());
String serviceName = input.readUTF();
String methodName = input.readUTF();
Class<?>[] parameterTypes = (Class<?>[]) input.readObject();
Object[] arguments = (Object[]) input.readObject();
Class serviceClass = serviceRegistry.get(serviceName);
if (serviceClass == null) {
throw new ClassNotFoundException(serviceName + " not found");
}
Method method = serviceClass.getMethod(methodName, parameterTypes);
Object result = method.invoke(serviceClass.newInstance(), arguments);
// 3.將執(zhí)行結(jié)果反序列化劣砍,通過(guò)socket發(fā)送給客戶端
output = new ObjectOutputStream(clent.getOutputStream());
output.writeObject(result);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (clent != null) {
try {
clent.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
客戶端的遠(yuǎn)程代理對(duì)象
public class RPCClient<T> {
public static <T> T getRemoteProxyObj(final Class<?> serviceInterface, final InetSocketAddress addr) {
// 1.將本地的接口調(diào)用轉(zhuǎn)換成JDK的動(dòng)態(tài)代理惧蛹,在動(dòng)態(tài)代理中實(shí)現(xiàn)接口的遠(yuǎn)程調(diào)用
return (T) Proxy.newProxyInstance(serviceInterface.getClassLoader(), new Class<?>[]{serviceInterface},
new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Socket socket = null;
ObjectOutputStream output = null;
ObjectInputStream input = null;
try {
// 2.創(chuàng)建Socket客戶端,根據(jù)指定地址連接遠(yuǎn)程服務(wù)提供者
socket = new Socket();
socket.connect(addr);
// 3.將遠(yuǎn)程服務(wù)調(diào)用所需的接口類刑枝、方法名香嗓、參數(shù)列表等編碼后發(fā)送給服務(wù)提供者
output = new ObjectOutputStream(socket.getOutputStream());
output.writeUTF(serviceInterface.getName());
output.writeUTF(method.getName());
output.writeObject(method.getParameterTypes());
output.writeObject(args);
// 4.同步阻塞等待服務(wù)器返回應(yīng)答,獲取應(yīng)答后返回
input = new ObjectInputStream(socket.getInputStream());
return input.readObject();
} finally {
if (socket != null) socket.close();
if (output != null) output.close();
if (input != null) input.close();
}
}
});
}
}
public class RPCTest {
public static void main(String[] args) throws IOException {
new Thread(new Runnable() {
public void run() {
try {
Server serviceServer = new ServiceCenter(8088);
serviceServer.register(HelloService.class, HelloServiceImpl.class);
serviceServer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
HelloService service = RPCClient.getRemoteProxyObj(HelloService.class, new InetSocketAddress("localhost", 8088));
System.out.println(service.sayHi("test"));
}
}
總結(jié)
RPC本質(zhì)為消息處理模型装畅,RPC屏蔽了底層不同主機(jī)間的通信細(xì)節(jié)靠娱,讓進(jìn)程調(diào)用遠(yuǎn)程的服務(wù)就像是本地的服務(wù)一樣。
這里實(shí)現(xiàn)的簡(jiǎn)單RPC框架是使用Java語(yǔ)言開(kāi)發(fā)掠兄,與Java語(yǔ)言高度耦合像云,并且通信方式采用的Socket是基于BIO實(shí)現(xiàn)的锌雀,IO效率不高,還有Java原生的序列化機(jī)制占內(nèi)存太多苫费,運(yùn)行效率也不高汤锨。可以考慮從下面幾種方法改進(jìn)百框。
- 可以采用基于JSON數(shù)據(jù)傳輸?shù)腞PC框架闲礼;
- 可以使用NIO或直接使用Netty替代BIO實(shí)現(xiàn);
- 使用開(kāi)源的序列化機(jī)制铐维,如Hadoop Avro與Google protobuf等柬泽;
- 服務(wù)注冊(cè)可以使用Zookeeper進(jìn)行管理,能夠讓?xiě)?yīng)用更加穩(wěn)定嫁蛇。