OSGI系列 服务注册

之前一直都是在说在blueprint中怎么发布(注册)服务以及获取服务,现在就来说说怎么通过代码来发布(注册)我们的服务和获取服务的

前提,需要引入咱们OSGI环境的依赖包:


一、发布(注册)服务

1、首先,我们来创建咱们的服务接口以及实现

服务接口:IService1.java

服务接口:Service1.java


2、然后,写一个Activator类,该类专用来注册服务的

public class Activator {
    protected static final Logger logger = LoggerFactory.getLogger(Activator.class);

    private BundleContext bundleContext;
    private Service1 service1;
    private Service2 service2;
    private ServiceRegistration serviceServiceRegistration;

    public void start() {
        Dictionary<String, String> properties = new Hashtable<>();
        properties.put("service.exported.interfaces","*");
        properties.put("service.exported.configs","service.rpc");
        serviceServiceRegistration =  bundleContext.registerService(Service1.class.getName(), service1, properties);
        serviceServiceRegistration =  bundleContext.registerService(Service2.class.getName(), service2, properties);
        logger.info("Score core started");
    }

    public void stop() {
        serviceServiceRegistration.unregister();
    }

    public void setBundleContext(BundleContext bundleContext) {
        this.bundleContext = bundleContext;
    }
    public void setService1(Service1 service1) {
        this.service1 = service1;
    }
    public void setService2(Service2 service2) {
        this.service2 = service2;
    }
    
    
}

二、获取服务

1、方式一(推荐)

ServiceTracker tracker = new ServiceTracker(context, Service1.class.getName(), null);
	tracker.open();
	Service1 service = (Service1) tracker.getService();
	if(service!=null)
	service.log(Service1.LOG_INFO,"ok");
	// 获取多个Service
	Object[] services = tracker.getServices();
	// 获取Service的数量
	int count = tracker.getTrackingCount();
	tracker.close();

2、方式二(最原始)

// 获取Service引用
	ServiceReference ref = context.getServiceReference(LogService.class.getName());
	if(ref!=null)
	{
		// 获取Service实例
		Service1 service = (Service1) context.getService(ref);
		if (service != null) {
			// 调用Service方法
			service.log(Service1.LOG_INFO, "ok");
			// 释放Service,在此之后不应该再继续使用Service实例
			context.ungetService(ref);
		}
	}


你可能感兴趣的:(osgi)