summaryrefslogtreecommitdiff
path: root/opendc-common/src/main/kotlin/org/opendc/common/utils/Redis.kt
blob: bf674a33642c1a20c12f15bb2dc1cbffe61df466 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package org.opendc.common.utils

import com.fasterxml.jackson.dataformat.toml.TomlMapper
import redis.clients.jedis.RedisClient
import redis.clients.jedis.StreamEntryID
import redis.clients.jedis.params.XReadParams
import java.util.Map
import java.util.Properties


/**
 * This class represents the Redis server instance.
 * @author Mateusz Kwiatkowski
 * @see <a href=https://redis.io/docs/latest/>https://redis.io/docs/latest/</a>
 *
 * @see <a href=https://redis.io/docs/latest/develop/data-types/streams/>https://redis.io/docs/latest/develop/data-types/streams/</a>
 *
 * @see <a href=https://www.javadoc.io/doc/redis.clients/jedis/latest/index.html>https://www.javadoc.io/doc/redis.clients/jedis/latest/index.html</a>
 */

@Suppress("DEPRECATION")
public class Redis private constructor() {
    private var jedis : RedisClient? = null
    private var properties : Properties? = null

    init {
        properties = TomlMapper().readerFor(Properties().javaClass).readValue(Kafka::class.java.getResource("/subscriber.toml"))
        jedis = RedisClient.create("redis://localhost:${properties?.getProperty("port")}")
    }

    public companion object {
        private var instance: Redis? = null

        public fun getInstance(): Redis? {
            if (instance == null) {
                instance = Redis()
            }
            return instance
        }
    }

    public fun readOne() {
        while(true) {
            val messages = jedis?.xread(
                XReadParams.xReadParams(),
                Map.of("${properties?.getProperty("table")}", StreamEntryID()
                ));

            if (messages != null) {
                for (stream in messages) {
                    for (entry in stream.value) {
                        if(entry.getFields().get("downtime") != null) {
                            entry.getFields().get("downtime")?.toDouble()?.let {
                                if (it > 0) {
                                    println("ID: " + entry.getID())
                                }
                            }
                        }
                    }
                }
            }
        }
            // https://redis.io/docs/latest/develop/use-cases/streaming/java-jedis/
            // In Redis you can subscribe to updates to a stream.
            // You should base your application off this.
            // You can listen for new items with XREAD

            // do not close for now
            //jedis.close()
        }
}