dubbo集成springboot


dubbo集成springboot

1.项目依赖




org.apache.dubbo
dubbo
${dubbo.version}



org.apache.dubbo
dubbo-dependencies-zookeeper
${dubbo.version}


slf4j-log4j12
org.slf4j


pom




org.springframework.boot
spring-boot-starter








org.springframework.boot
spring-boot-dependencies
${spring-boot.version}
pom
import


2.服务提供者

resource/spring目录下添加dubbo-provider.xml:

通过 Spring 配置引用远程服务

       xmlns:dubbo="http://dubbo.apache.org/schema/dubbo"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://dubbo.apache.org/schema/dubbo http://dubbo.apache.org/schema/dubbo/dubbo.xsd">












DemoServiceImpl:
import org.apache.dubbo.config.annotation.Service;
@Service
public class DemoServiceImpl implements DemoService {

public String sayHello(String name) {
return "Hello " + name;
}

}

如果上述配置文件里面使用方式,这里可以不用加@Service

方式,需加上@Service

Application:
@SpringBootApplication
@ImportResource(value = {"classpath:spring/dubbo-provider.xml"})
public class Application {
public static void main(String[] args) throws Exception{
SpringApplication.run(Application.class, args);

System.in.read();

}
}

 

3.服务消费者

resource/spring目录下添加dubbo-consumer.xml

通过 Spring 配置引用远程服务

       xmlns:dubbo="http://dubbo.apache.org/schema/dubbo"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://dubbo.apache.org/schema/dubbo http://dubbo.apache.org/schema/dubbo/dubbo.xsd">












SayService:
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class SayService {

@Reference
DemoService demoService;

public String say (String name) {

return demoService.sayHello(name);
}

}
若上述配置采用方式,此处使用duboo提供@Reference注解
若上述配置采用方式,此处使用@Autowired原生注解

Application:
@SpringBootApplication
@RestController
@ImportResource("classpath:spring/dubbo-consumer.xml")
public class Application {

@Autowired
SayService sayService;

@RequestMapping("/hello")
public String say(@RequestParam("name") String name) {
return sayService.say(name);
}

public static void main(String[] args) throws Exception{
SpringApplication.run(Application.class, args);


}
}

 

访问localhost:8081/hello?name=zhangsan, 返回 hello zhangsan, 消费成功

 

github地址: 

服务端: dubbo-springboot-xml-provider

消费端: dubbo-springboot-xml-consumer

接口: dubbo-xml-interface

https://github.com/wujinsen/dubbo-learning