Telegram Bots Help

Lesson 8. Integrating with Redis

Hi! Long time I haven't posted lessons. Sorry for that. Today we are integrating our high-load bot with a lighting fast database called Redis. I am using it for data that needs quick access.

Library

For driver, I chose Lettuce because of its popularity and good documentation. You can download it here or install with Maven:

<dependency> <groupId>io.lettuce</groupId> <artifactId>lettuce-core</artifactId> <version>6.3.2.RELEASE</version> </dependency>
implementation 'io.lettuce:lettuce-core:6.3.2.RELEASE'

Download `.jar` from here

Establish connection

Then, you need to connect to Redis:

RedisClient redisClient; StatefulRedisConnection<String, String> redisConnection; RedisCommands<String, String> syncCommands; redisClient = RedisClient.create("redis://localhost:6379/0"); // Format: redis://ip:post/dbNumber redisConnection = redisClient.connect(); syncCommands = this.redisConnection.sync();

Connection established

And that's all! Now you can execute commands like that:

syncCommands.get("key"); syncCommands.set("key", "value"); syncCommands.lrange("key", 0, -1);

Also, don't forget to close connection with Redis when you have done your work:

redisConnection.close(); redisClient.shutdown();

Quite a short lesson, but I think useful :D Thanks for your time, hope to see you soon!

Last modified: 23 November 2024