SpringCloud整合nacos和dubbo实现远程调用demo

在Dubbo框架中,服务提供者与消费者需使用相同接口路径,如com.example.demo.service。@Service注解用于提供者,而消费者通过@Reference调用。配置文件通常设定Nacos地址以进行服务发现,避免端口冲突,并在Nacos中查看服务暴露状态。消费者通过HTTP请求访问服务,如http://localhost:8433/hello。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

其中需要注意的点:

  1. 服务提供者和服务消费者在Dubbo框架中进行通信时,它们必须使用相同的接口路径。
    例如两个接口的包路径都是package com.example.demo.service;
  2. 注意如果提供者的接口用的是@Service,要查看引入的包路径是否为import org.apache.dubbo.config.annotation.Service;
  3. @Service(@DubboServie)添加在Impl上
  4. 一般来说,在配置文件的dubbo中配置了nacos的地址,则不需要再在discovery.server-addr的地址。但项目一般采用则是只需要在配置文件中配置nacos的地址,然后服务去nacos去获取配置文件的信息,例如dubbo配置。
  5. 注意 dubbo里的port不能被占用。
  6. 接口暴露成功后可以在nacos中看到。
    在这里插入图片描述

Demo

提供者

public interface HelloService {
    public String say();
}
@Service
public class HelloServiceImpl implements HelloService{
    @Override
    public String say() {
        return "Hello";
    }
}
@EnableDubbo
@SpringBootApplication
public class DemoApplication {

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

}
dubbo:
  scan:
    base-packages: com.example.demo.service
  protocol:
    name: dubbo
    port: 7702
  registry:
    address: nacos://localhost:8848
  consumer:
    timeout: 60000
    check: false
  application:
    name: ${spring.application.name}
  cloud:

消费者

public interface HelloService {
    public String say();
}
@RestController
public class HelloController {
    @Reference
    HelloService helloService;
    @GetMapping("/hello")
    public String hello(){
        return helloService.say();
    }
}
dubbo:
  scan:
    base-packages: com.ut.msfw1a.services.demo
  protocol:
    name: dubbo
    port: 30032
  registry:
    address: nacos://localhost:8848
  consumer:
    timeout: 60000
    check: false
  application:
    name: ${spring.application.name}
  cloud:

访问http://localhost:8433/hello即返回hello

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值