一、项目搭建
引入SpringBoot和Hprose相关依赖:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>springboot-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.hprose</groupId>
<artifactId>hprose-java</artifactId>
<version>2.0.32</version>
</dependency>
</dependencies>
</project>
二、服务端
2.1 准备Service
package com.example.service;
/**
* @Author: 98050
* @Time: 2019-06-19 20:40
* @Feature:
*/
public class Service {
public String sayHello(String name){
return "hello,"+ name;
}
}
2.2 准备Servlet
对外暴露服务接口
package com.example.controller;
import com.example.service.Service;
import hprose.common.HproseMethods;
import hprose.server.HproseServlet;
import javax.servlet.annotation.WebServlet;
/**
* @Author: 98050
* @Time: 2019-06-19 20:28
* @Feature:
*/
@WebServlet(urlPatterns = {"/hprose/sayHello"})
public class ServicePublish extends HproseServlet {
@Override
protected void setGlobalMethods(HproseMethods methods) {
super.setGlobalMethods(methods);
Service service = new Service();
methods.addMethod("sayHello",service);
}
}
2.3 扫描Servlet
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
/**
* @Author: 98050
* @Time: 2019-05-05 21:28
* @Feature:
*/
@SpringBootApplication
@ServletComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
三、客户端
3.1 准备接口
package com.example.test;
/**
* @Author: 98050
* @Time: 2019-06-19 20:18
* @Feature:
*/
public interface MyService {
String sayHello(String name);
}
3.2 远程调用
package com.example.test;
import hprose.client.HproseClient;
import hprose.client.HproseHttpClient;
/**
* @Author: 98050
* @Time: 2019-06-19 20:15
* @Feature:
*/
public class Test {
public static void main(String[] args) {
HproseClient client = new HproseHttpClient();
client.useService("http://localhost:8888/hprose/sayHello");
//通过接口调用
MyService service = client.useService(MyService.class);
String content = service.sayHello("jack");
System.out.println("远程RPC调用返回:" + content);
}
}