springboot2.X集成RPC服务Hprose(注解模式)

服务端(端口9989)

1.新建maven项目,引入hprose-jar

<!-- Hprose rpc通讯 -->
<dependency>
   <groupId>org.hprose</groupId>
   <artifactId>hprose-java</artifactId>
   <version>2.0.38</version>
</dependency>

2.业务处理类

//接口
public interface RpcService {
    String learnRpc(String message);
}

//实现类
@Service("rpcService")
public class RpcServiceImpl implements RpcService {
    public String learnRpc(String message) {
        return "hello rpc , " + message;
    }
}

3.对外暴露调用类

@WebServlet(urlPatterns = {"/hprose/learnRpc"})
public class RpcTestController extends HproseServlet {
	//方法一与方法二,任选其一
	
	//方法一(注解对象)
    @Autowired
    private RpcService rpcService;

    @Override
    protected void setGlobalMethods(HproseMethods methods) {
        super.setGlobalMethods(methods);
        methods.addMethod("learnRpc", rpcService);
    }


	////方法二(直接new对象)
	//@Override
    //protected void setGlobalMethods(HproseMethods methods) {
    //    super.setGlobalMethods(methods);
    //    RpcServiceImpl rpcService = new RpcServiceImpl();
    //    methods.addMethod("learnRpc", rpcService);
    //}
}

//注:暴露一个类的所有方法暴露
//a. @WebServlet加上所有方法名
//@WebServlet(urlPatterns = {"/api/v1.0.0/javatest/sayHello", "/api/v1.0.0/javatest/sayBye", "/api/v1.0.0/javatest/getUser"})
// b.addMethod("learnRpc", rpcService) 改成addInstanceMethods(rpcService)
//methods.addInstanceMethods(rpcService);//注册HelloService下所有的publice方法


4.应用启动类添加@ServletComponentScan,扫描对外暴露类

@SpringBootApplication
@ServletComponentScan
public class AuthorityApplication {

    public static void main(String[] args) {
        SpringApplication.run(AuthorityApplication.class, args);
    }

}

客户端(端口9790)

1.新建maven项目,引入hprose-jar

<!-- Hprose rpc通讯 -->
<dependency>
   <groupId>org.hprose</groupId>
   <artifactId>hprose-java</artifactId>
   <version>2.0.38</version>
</dependency>

2.准备接口,接收服务

public interface MyRpcService {
    String learnRpc(String message);
}

3.控制层调用服务端

@RestController
@CrossOrigin
@RequestMapping("/test")
public class TidbController {
   @RequestMapping(value = "/findHprose", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
    public JsonResult<String> findHprose(HttpServletRequest request) {
        HproseClient client = new HproseHttpClient();
        client.useService("http://localhost:9989/hprose/learnRpc");

        //通过接口调用
        MyRpcService service = client.useService(MyRpcService.class);
        String content = service.learnRpc("jack");
        //若learnRpc暴露了多个方法,可继续调用其他方法
        //String content2 = service.XXXXRpc("jack");
        return new JsonResult(SUCCESS_CODE, SUCCESS_MESSAGE, content);
    }
}


4.浏览器调用,返回结果
springboot2.X集成RPC服务Hprose(注解模式)_第1张图片

你可能感兴趣的:(springboot)