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.浏览器调用,返回结果
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值