我正在尝试从Microsoft实施eventhub示例,以从事件中心接收事件 https://docs.microsoft.com/fr-fr/azure/event-hubs/event-hubs-java-get-started-receive-eph
我已经在Spring Boot应用程序中创建了这些类,并且能够打印出消息。
我想处理这些事件,所以我决定创建一个服务。 @Autowired无法从上下文加载服务。我不知道为什么;
@SpringBootApplication
public class EventProcessorSample
{
public static void main(String args[]) throws InterruptedException, ExecutionException
{
############
host.registerEventProcessor(EventProcessor.class, options)
.whenComplete((unused, e) ->
{
#######
System.out.println("End of sample");
}
问题在这里:服务为NULL 我已经尝试了@Component或@Service到此类。.但是未填充服务。
public static class EventProcessor implements IEventProcessor
{
private int checkpointBatchingCount = 0;
@Autowired
ProcessingService processingservice;
// onEvents is called when events are received on this partition of the Event Hub.
@Override
public void onEvents(PartitionContext context, Iterable<EventData> events) throws Exception
{
System.out.println("SAMPLE: Partition " + context.getPartitionId() + " got event batch");
int eventCount = 0;
for (EventData data : events)
{
try
{
processingservice.process(new String(data.getBytes(), "UTF8"));
}
catch (Exception e)
{
System.out.println("Processing failed for an event: " + e.toString());
}
}
System.out.println("SAMPLE: Partition " + context.getPartitionId() + " batch size was " + eventCount + " for host " + context.getOwner());
}
}
服务:
@Service
public class ProcessingService {
public void process(String myMessage){
//Call Repository
}
}
是因为registerHostProcessor使用类类型作为参数吗? 我如何加载服务以进行处理并随后调用存储库?
谢谢。
打包是简单的springboot应用程序
src/main/java
|
+-- EventProcessorSample
|
+-- service
| |
| +-- ProcessingService
|
+-- processor
| |
| +-- EventProcessor
|
+-- repository
| |
+ |-- MyRepository
答案 0 :(得分:2)
您需要从以下位置更改注册代码:
host.registerEventProcessor(EventProcessor.class, options)
到
@Autowired
private EventProcessorFactory eventProcessorFactory;
...
host.registerEventProcessorFactory(eventProcessorFactory)
哪里
@Component
public class EventProcessorFactory implements IEventProcessorFactory<EventProcessor> {
@Autowired
ProcessingService processingservice;
@Override
public EventProcessor createEventProcessor(PartitionContext context) throws Exception {
return new EventProcessor(processingservice);
}
}
EventProcessorFactory是Spring管理生命周期的组件。您可以将所需的任何东西注入EventProcessorFactory,然后在工厂方法内创建EventProcessor时将其传递给EventProcessor。 这样,您就可以开始控制EventProcessor实例的创建。
希望这会有所帮助!
答案 1 :(得分:0)
您的EventProcessor
类也应该是Spring bean-添加@Component
并确保Spring的组件扫描机制可以找到带注释的类...
@Component
public class EventProcessor implements IEventProcessor
{
private int checkpointBatchingCount = 0;
private ProcessingService processingservice;
// constructor injection of mandatory dependencies
public EventProcessor(ProcessingService processingService) {
this.processingService = processingService;
}
// onEvents is called when events are received on this partition of the Event Hub.
@Override
public void onEvents(PartitionContext context, Iterable<EventData> events) throws Exception
{
//....
}
}