WIP
[demos/kafka/chat] / src / main / java / de / juplo / kafka / chat / backend / persistence / inmemory / InMemoryServicesConfiguration.java
1 package de.juplo.kafka.chat.backend.persistence.inmemory;
2
3 import de.juplo.kafka.chat.backend.ChatBackendProperties;
4 import de.juplo.kafka.chat.backend.domain.ChatHome;
5 import de.juplo.kafka.chat.backend.persistence.StorageStrategy;
6 import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
7 import org.springframework.context.annotation.Bean;
8 import org.springframework.context.annotation.Configuration;
9
10 import java.time.Clock;
11 import java.util.stream.IntStream;
12
13
14 @ConditionalOnProperty(
15     prefix = "chat.backend",
16     name = "services",
17     havingValue = "inmemory",
18     matchIfMissing = true)
19 @Configuration
20 public class InMemoryServicesConfiguration
21 {
22   @Bean
23   @ConditionalOnProperty(
24       prefix = "chat.backend.inmemory",
25       name = "sharding-strategy",
26       havingValue = "none",
27       matchIfMissing = true)
28   ChatHome noneShardingChatHome(StorageStrategy storageStrategy)
29   {
30     return new SimpleChatHome(storageStrategy.read());
31   }
32
33   @Bean
34   @ConditionalOnProperty(
35       prefix = "chat.backend.inmemory",
36       name = "sharding-strategy",
37       havingValue = "kafkalike")
38   ChatHome kafkalikeShardingChatHome(
39       ChatBackendProperties properties,
40       StorageStrategy storageStrategy)
41   {
42     int numShards = properties.getInmemory().getNumShards();
43     SimpleChatHome[] chatHomes = new SimpleChatHome[numShards];
44     IntStream
45         .of(properties.getInmemory().getOwnedShards())
46         .forEach(shard -> chatHomes[shard] = new SimpleChatHome(shard, storageStrategy.read()));
47     ShardingStrategy strategy = new KafkaLikeShardingStrategy(numShards);
48     return new ShardedChatHome(chatHomes, strategy);
49   }
50
51   @Bean
52   InMemoryChatRoomFactory chatRoomFactory(
53       ShardingStrategy strategy,
54       Clock clock,
55       ChatBackendProperties properties)
56   {
57     return new InMemoryChatRoomFactory(
58         strategy,
59         clock,
60         properties.getChatroomBufferSize());
61   }
62
63   @ConditionalOnProperty(
64       prefix = "chat.backend.inmemory",
65       name = "sharding-strategy",
66       havingValue = "none",
67       matchIfMissing = true)
68   @Bean
69   ShardingStrategy defaultShardingStrategy()
70   {
71     return chatRoomId -> 0;
72   }
73
74   @ConditionalOnProperty(
75       prefix = "chat.backend.inmemory",
76       name = "sharding-strategy",
77       havingValue = "kafkalike")
78   @Bean
79   ShardingStrategy kafkalikeShardingStrategy(ChatBackendProperties properties)
80   {
81     return new KafkaLikeShardingStrategy(
82         properties.getInmemory().getNumShards());
83   }
84 }