Dubbo integrates with Spring to achieve service publishing and referencing through annotations, simplifying the development process
1、 Maven coordinates and dependency class library introduction:
-Dubbo Dependency:
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>2.7.0</version>
</dependency>
Dubbo is a high-performance Java RPC framework open-source by Alibaba that enables remote service invocation and distributed service governance.
-Spring dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
Spring is a lightweight Java development framework that makes it easier for developers to develop Java applications.
2、 Sample integration of Dubbo and Spring:
1. Define service interfaces:
public interface HelloService {
String sayHello(String name);
}
2. Implement service interfaces:
@Service
public class HelloServiceImpl implements HelloService {
@Override
public String sayHello(String name) {
return "Hello, " + name;
}
}
3. Configure the integration of Dubbo and Spring (in the application. properties or application. yml file):
yaml
#Dubbo Service Port
dubbo:
protocol:
port: 20880
#Zookeeper connection address
zookeeper:
address: 127.0.0.1:2181
4. Startup class:
@SpringBootApplication
@Enable Dubbo//Enable Dubbo
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
5. Service Provider:
@Service
public class HelloServiceImpl implements HelloService {
@Override
public String sayHello(String name) {
return "Hello, " + name;
}
}
6. Service consumer:
@RestController
public class HelloController {
//Referencing Remote Services
@Reference
private HelloService helloService;
@GetMapping("/hello")
public String hello(@RequestParam String name) {
//Calling remote services
return helloService.sayHello(name);
}
}
7. Write test classes and initiate testing:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HelloServiceTest {
@DubboReference
private HelloService helloService;
@Test
public void testSayHello() {
String result = helloService.sayHello("Alice");
Assert.assertEquals("Hello, Alice", result);
}
}
3、 Summary:
Through the integration of Dubbo and Spring, developers can use annotations to publish and reference services, reducing the tedious configuration process and simplifying the development process. Dubbo, as a high-performance Java RPC framework, can achieve remote service invocation, while Spring, as a lightweight Java development framework, can make it easier for developers to develop Java applications. The advantage of this integration approach is that it can better utilize the features of Dubbo and Spring, improving development efficiency.