-
Notifications
You must be signed in to change notification settings - Fork 1
/
Service.java
54 lines (43 loc) · 1.46 KB
/
Service.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package cn.jiuyou2020;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
// 服务接口
interface Service {
String sayHello(String name);
}
// 服务实现类
class ServiceImpl implements Service {
@Override
public String sayHello(String name) {
return "Hello, " + name;
}
}
// 动态代理处理器
class RpcInvocationHandler implements InvocationHandler {
private final Object target;
public RpcInvocationHandler(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 在这里加入远程调用逻辑
System.out.println("Calling remote service...");
// 模拟远程调用,实际调用本地的服务实现
Object result = method.invoke(target, args);
System.out.println("Remote service called successfully.");
return result;
}
}
// 客户端代码
class RpcClient {
public static void main(String[] args) {
// 创建服务实现
Service service = new ServiceImpl();
// 创建动态代理
Service proxy = (Service) Proxy.newProxyInstance(service.getClass().getClassLoader(), service.getClass().getInterfaces(), new RpcInvocationHandler(service));
// 通过代理调用服务
String response = proxy.sayHello("Alice");
System.out.println("Response: " + response);
}
}