Spring Cloud Alibaba教程:Dubbo

129 阅读1分钟

构建服务接口

public interface HelloService {

	String hello();
	
}

构建服务提供方

import org.apache.dubbo.config.annotation.Service;
import com.learn.nacos_provider.service.HelloService;
@Service
public class HelloServiceImpl implements HelloService {

	@Override
	public String hello() {
		return "Hello, Nacos and Dubbo";
	}

}

@SpringBootApplication
@EnableDiscoveryClient
public class App {
	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}
}

spring.application.name=alibaba-dubbo-server
server.port=8001
spring.cloud.nacos.discovery.server-addr=192.168.100.178:8848
# 指定 Dubbo 服务实现类的扫描基准包
dubbo.scan.base-packages=com.learn.nacos_provider.service
dubbo.protocol.name=dubbo
dubbo.protocol.port=-1
dubbo.registry.address=spring-cloud://192.168.100.178:8848

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-dubbo</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
必须包含spring-boot-starter-actuator包,不然启动会报错
dubbo.scan.base-packages: 指定 Dubbo 服务实现类的扫描基准包

构建服务消费者

@SpringBootApplication
@EnableDiscoveryClient
public class App {
	public static void main(String[] args) {
		System.setProperty("nacos.standalone", "true");
		SpringApplication.run(App.class, args);
	}
	
	@RestController
    static class TestController {
 
        @Reference
        HelloService helloService;
 
        @GetMapping("/test")
        public String test() {
            return helloService.hello();
        }
    }
}

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-dubbo</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>
必须包含spring-boot-starter-web包,不然启动会报错

dubbo.cloud.subscribed-services:表示要订阅服务的服务名,默认为*,指全部服务