spring rpc demo
时间: 2023-05-23 07:07:00 浏览: 50
A:以下是一个简单的 Spring RPC 示例:
1.创建一个 Maven 项目并添加以下依赖项:
```
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
</dependencies>
```
2.创建一个接口:
```
public interface CalculatorService {
int add(int a, int b);
}
```
3.创建一个实现类:
```
public class CalculatorServiceImpl implements CalculatorService {
@Override
public int add(int a, int b) {
return a + b;
}
}
```
4.在 Spring 配置文件中定义 Bean:
```
<bean id="calculatorService" class="com.example.CalculatorServiceImpl" />
```
5.创建一个 Spring Controller:
```
@Controller
public class CalculatorController {
@Autowired
private CalculatorService calculatorService;
@RequestMapping(value="/add", method=RequestMethod.POST)
@ResponseBody
public int add(@RequestParam("a") int a, @RequestParam("b") int b) {
return calculatorService.add(a, b);
}
}
```
6.在 Spring 配置文件中注册 Controller:
```
<mvc:annotation-driven />
<context:component-scan base-package="com.example" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
```
7.对外提供 RPC 服务,使用 RMI 或 Hessian 等协议。
```
<bean id="calculatorServiceExporter" class="org.springframework.remoting.rmi.RmiServiceExporter">
<property name="serviceName" value="CalculatorService" />
<property name="service" ref="calculatorService" />
<property name="serviceInterface" value="com.example.CalculatorService" />
<property name="registryPort" value="1099" />
</bean>
<!-- 或者 -->
<bean id="calculatorServiceExporter" class="org.springframework.remoting.caucho.HessianServiceExporter">
<property name="service" ref="calculatorService" />
<property name="serviceInterface" value="com.example.CalculatorService" />
</bean>
```
8.在客户端通过 RMI 或 Hessian 等协议访问 CalculatorService。
```
// RMI
Remote remoteService = Naming.lookup("rmi://localhost:1099/CalculatorService");
CalculatorService calculatorService = (CalculatorService) UnicastRemoteObject.exportObject(remoteService, 0);
// Hessian
String url = "http://localhost:8080/CalculatorService";
HessianProxyFactory factory = new HessianProxyFactory();
CalculatorService calculatorService = (CalculatorService) factory.create(CalculatorService.class, url);
```