代理模式:静态代理和动态代理
静态代理
/**
* 静态代理
*
* @author nami404
* * @date 2024/6/25 18:32
*/
public class UserServiceProxy implements UserService {
public User getUser(User user) {
// 指定序列化器
JdkSerializer serializer = new JdkSerializer();
// 发请求
RpcRequest rpcRequest = RpcRequest.builder()
.serviceName(UserService.class.getName())
.methodName("getUser")
.parameterType(new Class[]{User.class})
.args(new Object[]{user})
.build();
try {
byte[] bodyBytes = serializer.serialize(rpcRequest);
byte[] result;
try (HttpResponse httpResponse = HttpRequest.post("http://localhost:8080")
.body(bodyBytes)
.execute()) {
result = httpResponse.bodyBytes();
}
RpcResponse rpcResponse = serializer.deserialize(result, RpcResponse.class);
return (User) rpcResponse.getData();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
UserService接口:
public interface UserService {
/**
* 获取用户
*
* @param user
* @return
*/
User getUser(User user);
}
动态代理
/**
* 服务代理(JDK 动态代理)
*
* @author nami404
* * @date 2024/6/25 18:44
*/
public class ServiceProxy implements InvocationHandler {
/**
* 调用代理
*
* @return
* @throws Throwable
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//指定序列化器
JdkSerializer serializer = new JdkSerializer();
//构造请求
RpcRequest rpcRequest = RpcRequest.builder()
.serviceName(method.getDeclaringClass().getName())
.methodName(method.getName())
.parameterType(method.getParameterTypes())
.args(args)
.build();
try {
// 序列化
byte[] bodyBytes = serializer.serialize(rpcRequest);
// 发送请求
// todo 注意,这里地址是硬编码(需要使用注册中心和服务发现机制解决)
try (HttpResponse httpResponse = HttpRequest.post("http://localhost:8080")
.body(bodyBytes)
.execute()) {
byte[] result = httpResponse.bodyBytes();
// 反序列化
RpcResponse rpcResponse = serializer.deserialize(result, RpcResponse.class);
return rpcResponse.getData();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
工厂模式:
/**
* 服务代理工厂(用于创建代理对象)
* @author nami404
* * @date 2024/6/25 18:44
*/
public class ServiceProxyFactory {
/**
* 根据服务类获取代理对象
*
* @param serviceClass
* @return
* @param <T>
*/
public static <T> T getProxy(Class<T> serviceClass) {
return (T) Proxy.newProxyInstance(serviceClass.getClassLoader(), new Class[]{serviceClass}, new ServiceProxy());
}
}
实际调用方式:
UserService userService = ServiceProxyFactory.getProxy(UserService.class);