Dubbo——微服务框架(单体式->分布式->微服务)_Strine的博客-CSDN博客
基于上一篇讲的我们现在使用原生API实现一下生产者发布服务和消费者消费服务;
product-api模块
实体类
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class Product implements Serializable {
private Long id;
private String name;
}
Service接口
public interface IProductService {
void handleAll();
Product get(Long id);
}
product-server模块
模拟mapper操作数据库
public abstract class ProductData {
//模拟数据库
private static final Map<Long, Product> productMap = new HashMap<>();
static {
productMap.put(1L,new Product(1L,"小米"));
productMap.put(2L,new Product(2L,"苹果"));
productMap.put(3L,new Product(3L,"华为"));
}
public static Product getProduct(Long id){
return productMap.get(id);
}
}
Service实现类
public class ProductServiceImpl implements IProductService {
@Override
public void handleAll() {
System.out.println("获取所有的产品");
}
@Override
public Product get(Long id) {
return ProductData.getProduct(id);
}
}
生产者发布服务
public class ProductApp {
/**
* 发布Product-server这个服务
* */
@Test
public void productTest() throws IOException {
//1.创建出来有一个对象并且指定名字
ApplicationConfig acc = new ApplicationConfig("product-server");
//2.创建协议对象
ProtocolConfig dubbo = new ProtocolConfig("dubbo", 20880);
//3.创建zookeeper的客户端对象,指定ip,端口等等
RegistryConfig registryConfig = new RegistryConfig("zookeeper://127.0.0.1:2181");
//4.创建出来发布服务的对象和真实服务对象
ServiceConfig<IProductService> serviceConfig = new ServiceConfig<>();
serviceConfig.setApplication(acc);
serviceConfig.setProtocol(dubbo);
serviceConfig.setRegistry(registryConfig);
serviceConfig.setInterface(IProductService.class);
serviceConfig.setRef(new ProductServiceImpl());
//5.发布服务
serviceConfig.export();
//使用阻塞模拟服务器正在运行。让它持续不断的提供服务
System.in.read();
}
}
消费者消费服务
public class WebsiteApp {
@Test
public void websiteTest(){
//1:创建应用配置对象,设置名称
ApplicationConfig applicationConfig = new ApplicationConfig("website");
//2:创建注册中心配置对象,设置注册中心地址
RegistryConfig registryConfig = new RegistryConfig("zookeeper://127.0.0.1:2181");
//3:创建引用配置对象,设置引用参数
ReferenceConfig<IProductService> referenceConfig = new ReferenceConfig<>();
referenceConfig.setApplication(applicationConfig);
referenceConfig.setRegistry(registryConfig);
referenceConfig.setInterface(IProductService.class);
/*如果没有注册中心则需要配置URL地址
referenceConfig.setUrl("服务地址");*/
//4:引用Dubbo提供的动态代理对象
IProductService productService = referenceConfig.get();
//5:调用方法获取结果
Product result = productService.get(1L);
System.out.println("=========================================");
System.out.println("获取到id为:"+result.getId()+"的产品:"+result.getName());
}
}
如果我们的实体类没有实现Serializable序列化接口就会出现以下错误:
因此我们实现序列化接口(注意有本地缓存,需要重启生产者服务);
这种方式并不要求大家去记住,但是我们需要理解它底层在进行远程调用的时候实际就是做这些配置。