使用dubbo注解方式暴露接口
时间: 2023-10-20 15:17:50 浏览: 99
要使用Dubbo注解的方式暴露接口,需要按照以下步骤进行:
1. 在Dubbo配置文件中,添加`<dubbo:annotation package="com.example.service"/>`,指定需要扫描的包名。
2. 在需要暴露的接口上添加`@Service`注解,该注解来自Dubbo。
3. 在Dubbo配置文件中,添加`<dubbo:protocol name="dubbo" port="20880"/>`,指定Dubbo所使用的协议和端口。
4. 启动Dubbo服务。
下面是一个示例代码:
1. 服务接口
```java
public interface HelloService {
String sayHello(String name);
}
```
2. 服务实现类
```java
@Service
public class HelloServiceImpl implements HelloService {
public String sayHello(String name) {
return "Hello, " + name;
}
}
```
3. Dubbo配置文件
```xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:dubbo="http://dubbo.apache.org/schema/dubbo"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://dubbo.apache.org/schema/dubbo
http://dubbo.apache.org/schema/dubbo/dubbo.xsd">
<!-- 指定需要扫描的包名 -->
<dubbo:annotation package="com.example.service"/>
<!-- 指定Dubbo所使用的协议和端口 -->
<dubbo:protocol name="dubbo" port="20880"/>
<!-- 暴露服务 -->
<bean id="helloService" class="com.example.service.impl.HelloServiceImpl"/>
</beans>
```
4. 启动Dubbo服务
```java
public class DubboProvider {
public static void main(String[] args) throws Exception {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:dubbo-provider.xml");
context.start();
System.in.read();
}
}
```
启动成功后,可以使用Dubbo提供的工具Dubbo Admin来查看已经暴露的服务。
阅读全文
相关推荐















