Dubbo快速入门

发布于:2025-02-10 ⋅ 阅读:(39) ⋅ 点赞:(0)

整合Spring和SpringMVC
在这里插入图片描述

服务提供者:

package com.hwt.service.impl;

import com.hwt.service.UserService;
import org.apache.dubbo.config.annotation.Service;

//@Service //交给spring ioc管理
@Service //将这个类提供的方法(服务)对外发布。将访问的地址、ip、端口、路径、注册到注册中心中
public class UserServiceImpl implements UserService {
    @Override
    public String sayHello() {
        return "hello dubbo!";
    }
}

服务消费者:

package com.hwt.controller;

import com.hwt.service.UserService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {

    //注入Service
    //@Autowired

    /*
     远程注入
        1.从zookeeper注册中心获取userService的访问url
        2.进行远程调用rpc
        3.将结果封装为一个代理对象,给变量赋值
     */
    @Reference
    private UserService userService;


    @RequestMapping("/sayHello")
    public String sayHello(){
        return userService.sayHello();
    }

}

创建一样的接口userService:

package com.hwt.web.service;

public interface UserService {
    String sayHello();
}

如果调用的接口很多,为方便管理以及提高开发效率,可以创建一个公共模块,用于定义、管理远程调用的接口,如dubbo-interfance

package com.hwt.service;

public interface UserService {

    public String sayHello();
}

服务提供者和消费者只需要引入该模块即可

	<!--公共接口依赖-->
	<dependency>
      <groupId>com.hwt</groupId>
      <artifactId>dubbo-interface</artifactId>
      <version>1.0-SNAPSHOT</version>
    </dependency>