Our system uses Redis to load and cache news and games that are fetched from the internet or the database. The Redis package is defined in com.goodboards.redis which is defined in the redis-interface component.
We use two Redis lists, Games and News to push and cache records as needed and use a rpop (right pop) to retrieve elements from the list.
- If you have pip installed you can use
pip install redisto install Redis on you computer. - Start redis server by using
redis-serverin terminal. - Once the server has started, open a new terminal tab and
enter redis-cli, enter the command
PINGand Redis will respond withPONGconfirming the server has started. - That's it, installation is complete :D
- The Goodboards app will access redis through a
environment (env) variable called
REDIS_URL, so for Redis to work properly you will need to set the env variable. On Mac,
you can useexport REDIS_URL=redis://localhost:6379to confirm the variable has been set useecho $REDIS_URL - And that's it ;D
RedisInterface- Class for accessing Redis Queue
SystemWrapper- Contains utility functions to access env variables.
// Get REDIS_URL env variable value
private val redisHost = SystemWrapper.getenv("REDIS_URL")
// Create a redis client for the given host url
private val redisClient: RedisClient = RedisClient.create(redisHost)
// Connect the client to redis server at the host url, creating a connection
private val connection: StatefulRedisConnection<String, String> = redisClient.connect()
// connection.sync returns a RedisCommands instance that us to synchronously execute Redis command over the connection
private val redisCommands: RedisCommands<String, String> = connection.sync()fun pushToList(name: String, values: List<String> {
redisCommands.lpush(name, *values.toTypedArray())
}This function takes two arguments, a name and a list of string. Then it converts this list of strings to an array of strings, spreads it using the * spread-operator pushes all the strings to the start or left the list named 'name' on the Redis server. If the there is no list with that name then a new list is created with that name.
fun getFromList(name: String, count: Long = 1): List<String> {
return redisCommands.rpop(name, count)
}This method takes two arguments name (name of the list) and count (number of elements to get from the right side of the list). The default value of count is set to 1.
fun close() {
connection.close()
redisClient.shutdown()
}This method is used to close the Redis connection and shutdown the Redis client. It does not take any parameters.
import com.goodboards.redis.*
val redisInterface = RedisInterface()
redisInterface.pushToList("Games", listOf<String>("{name: 'Chess', desc:'Good Game'}"))
println(redisInterface.rpop("Games"))
// prints -> "{name: 'Chess', desc:'Good Game'}"