你们要的基于自己实现的rpc框架的服务-消费项目来了!
1. 工程结构
父module
- my_rpc:管理所有子模块,依赖自定义rpc框架
子module
- my_rpc_api:提供服务的api接口
- my_rpc_server:服务端,实现api的接口,给客户端提供真实服务
- my_rpc_client:客户端,调用api接口,获取服务端服务
2. 依赖
父module
- my_rpc:管理所有子模块,依赖自定义rpc框架
<dependencies>
<dependency>
<groupId>com.fyp</groupId>
<artifactId>rpc_fyp_framework</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
注意: 父项目一般都为pom方式,子项目才为war和jar
子module
- my_rpc_api:提供服务的api接口
- my_rpc_server:服务端,实现api的接口,给客户端提供真实服务
<dependencies>
<dependency>
<groupId>com.fyp</groupId>
<artifactId>my_rpc_api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
- my_rpc_client:客户端,调用api接口,获取服务端服务
<dependencies>
<dependency>
<groupId>com.fyp</groupId>
<artifactId>my_rpc_api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
3 工程项目
父module
- my_rpc:管理所有子模块,依赖自定义rpc框架
子module
package com.fyp.service;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface UserService extends Remote {
String getUser(String name) throws RemoteException;
}
- my_rpc_server:服务端,实现api的接口,给客户端提供真实服务
(1)服务启动器
package com.fyp;
import com.fyp.rpc.FypRpcFactory;
import com.fyp.service.UserService;
import com.fyp.service.impl.UserServiceImpl;
public class ServerApplication {
public static void main(String[] args) throws Exception {
UserService userService = new UserServiceImpl();
FypRpcFactory.registerService(UserService.class,userService);
}
}
(2)服务实现类
package com.fyp.service.impl;
import com.fyp.service.UserService;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class UserServiceImpl extends UnicastRemoteObject implements UserService {
public UserServiceImpl() throws RemoteException {
super();
}
@Override
public String getUser(String name) throws RemoteException {
System.out.println("要查询的用户是:" + name);
return "{\"name\":\""+name+"\",\"age\":20,\"gender\":\"男\"}";
}
}
(3)zk信息配置
fyp-rpc.properties
registry.port=9999
zk.server=localhost:2181
zk.sessionTimeout=20000
- my_rpc_client:客户端,调用api接口,获取服务端服务
(1)客户端
package com.fyp;
import com.fyp.rpc.FypRpcFactory;
import com.fyp.service.UserService;
import org.apache.zookeeper.KeeperException;
import java.io.IOException;
import java.rmi.NotBoundException;
public class TestRpcClient {
public static void main(String[] args) {
try {
UserService userService = FypRpcFactory.getServiceProxy(UserService.class);
System.out.println(userService.getClass().getName());
String result = userService.getUser("管理员");
System.out.println("远程服务返回查询结果:" + result);
} catch (IOException e) {
e.printStackTrace();
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (NotBoundException e) {
e.printStackTrace();
}
}
}
(2)zk信息配置
zk.server=localhost:2181?
|