dubbo-api模块
在dubbo-api模块中新建pojo实体类包和service包,并在包里面编写对应的代码
public class User implements Serializable {
private Integer id;
private String username;
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
public interface UserService {
User findUser(Integer userId) throws RemoteException;
}
dubbo-provider模块
新建service包,编写userServiceImpl.java将服务暴露出来(注意Reference包有两个,选择正确的)
import com.alibaba.dubbo.config.annotation.Reference;
import com.wantl.api.service.UserService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class UserInit implements CommandLineRunner {
@Reference(interfaceClass = UserService.class)
private UserService userService;
@Override
public void run(String... args) throws Exception {
System.out.println(userService.findUser(2));
}
}
新建启动类,加上@EnableDubboConfiguration
开启Dubbo配置
@SpringBootApplication
@EnableDubboConfiguration
public class DubboProviderApplication {
public static void main(String[] args) {
SpringApplication.run(DubboProviderApplication.class,args);
}
}
在main目录下新建一个resources文件夹(和java目录同级,在main目录下),标记为资源目录,
新建application.yml,采用multicas注册中心
server:
port: 8081
spring:
application:
name: dubbo
dubbo:
server: true
application:
name: provider
registry:
address: multicast://224.5.6.7:1234
protocol:
name: dubbo
port: 20880
scan: com.wantl.provider.service
dubbo-consumer模块
编写UserInit.java
import com.alibaba.dubbo.config.annotation.Reference;
import com.wantl.api.service.UserService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class UserInit implements CommandLineRunner {
@Reference(interfaceClass = UserService.class)
private UserService userService;
@Override
public void run(String... args) throws Exception {
System.out.println(userService.findUser(2));
}
}
启动类
@SpringBootApplication
@EnableDubboConfiguration
public class DubboConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(DubboConsumerApplication.class,args);
}
}
application.yml
server:
port: 8082
spring:
application:
name: dubbo
dubbo:
server: true
application:
name: consumer
registry:
address: multicast://224.5.6.7:1234
protocol:
name: dubbo
port: 20880
scan: com.wantl.consumer
编写完成后,先启动DubboProviderApplication启动类,再启动DubboConsumerApplication启动类