项目描述:
我有一个简单的OSGi演示项目。域是一个具有多种传感器类型的气象站。每个传感器都将其数据发送到气象站。通过API,数据通过一个地块在网站上公开和可视化。
目标:
例句:我目前有三种不同的传感器类型。一个用来测量风速、温度和湿度的仪器。气象站应该有多个风传感器实例(Cardinality.MULTIPLE)。
现状:
目前,我正在通过创建一个WindSpeedSensor和一个WindSpeedAdvancedSensor服务来解决这个问题。我已经为Apache实现了一个自定义命令,在这里我可以向我的服务发送特定的配置命令。因此,传感器可以被配置为在特定范围内生成测量值。
期望条件:
一个最佳的解决方案是通过Karaf启动额外的WindSpeedSensor实例。不应该需要人为的WindSpeedSensors来实现WeatherStation类多个服务的目标。
问题:
我怎样才能做到这一点?我是OSGi和声明性服务的新手,我很好奇OSGi方面的专家是如何解决这个问题的。提前感谢您的时间和反馈。
发布于 2021-08-11 16:06:58
我只在Karaf中使用了OSGi,所以在其他环境中,这可能会有所不同。
如果每个配置文件都需要OSGi服务,则可以使用声明性服务注释来设置此类服务,例如,如下所示。
import org.osgi.framework.BundleContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.ConfigurationPolicy;
import org.osgi.service.metatype.annotations.Designate;
import com.example.service.config.ExampleServiceConfig;
@Component(
immediate = true, service = ExampleService.class,
configurationPolicy = ConfigurationPolicy.REQUIRE,
configurationPid = "com.example.service.ExampleService"
)
@Designate(ocd = ExampleServiceConfig.class, factory = true)
public class ExampleService {
@Activate
public void onServiceActivate(BundleContext context, ExampleServiceConfig config){
System.out.println(config.hello_message());
}
}然后为服务定义类型安全配置,例如:
import org.osgi.service.metatype.annotations.ObjectClassDefinition;
@ObjectClassDefinition(name = "ExampleService Configuration")
public @interface ExampleServiceConfig {
String hello_message() default "hello world";
String osgi_jndi_service_name() default "unique.service.name";
}由于单例配置使用像<configurationPid>.cfg工厂配置这样的文件名,所以使用<configurationPid>-<InstanceName>.cfg格式,因此要在上面创建两个ExampleService实例,您可以创建以下配置:
com.example.service.ExampleService-InstanceA.cfg
hello.message=Hello from Instance A
osgi.jdni.service.name=InstanceAcom.example.service.ExampleService-InstanceB.cfg
hello.message=Hello from Instance B
osgi.jdni.service.name=InstanceB至少在Karaf中,这将创建两个ExampleService实例和两个配置,具有某种类型的惟一guid (而不是实例名称)。要引用特定的服务实例,可以从引用注释中使用目标属性。
@Reference(
target = "(osgi.jdni.service.name=InstanceA)"
)
ExampleService exampleService;发布于 2021-03-16 14:25:45
您可以使用工厂配置 (参见https://docs.osgi.org/specification/osgi.cmpn/7.0.0/service.component.html#service.component-deployment)。对于工厂pid下的每个配置,DS将创建一个组件配置。这允许根据配置管理中的工厂配置多次创建一个组件。
https://stackoverflow.com/questions/66653848
复制相似问题