Add module devlok-redis and developed devlok-databases

This commit is contained in:
Weapie 2024-07-06 16:50:01 +02:00
parent 47cf05af2d
commit 99dfee7bf8
27 changed files with 1102 additions and 8 deletions

View File

@ -1,12 +1,18 @@
import org.gradle.api.credentials.PasswordCredentials
plugins {
id("java-library")
id("maven-publish")
id("com.github.johnrengelman.shadow") version("8.1.1")
}
allprojects {
apply(plugin = "java-library")
apply(plugin = "maven-publish")
apply(plugin = "com.github.johnrengelman.shadow")
group = "de.weapie"
version = "2024.07.02-01"
version = "2024.07.06-02"
repositories {
mavenCentral()
@ -30,4 +36,31 @@ allprojects {
options.encoding = "UTF-8"
options.isIncremental = true
}
publishing {
repositories {
maven {
name = "jfHomeRepoPrivate"
url = uri("https://repo.jf.home/private")
credentials(PasswordCredentials::class)
authentication {
create<BasicAuthentication>("basic")
}
}
}
publications {
create<MavenPublication>("maven") {
groupId = "${project.group}"
artifactId = "${project.name}"
version = "${project.version}"
from(components["java"])
}
}
}
tasks.shadowJar {
archiveBaseName.set("${project.name}")
archiveVersion.set("${project.version}")
archiveFileName.set("${archiveBaseName.get()}-${archiveVersion.get()}.jar")
}
}

View File

@ -0,0 +1,71 @@
package de.weapie.devlok.database;
import de.weapie.devlok.database.config.DatabaseConfig;
import de.weapie.devlok.database.config.DatabaseType;
import de.weapie.devlok.database.config.module.MongoDBAuthenticationModule;
import de.weapie.devlok.database.config.module.MySQLAuthenticationModule;
import de.weapie.devlok.database.mongodb.MongoDBDatabase;
import de.weapie.devlok.database.mysql.MySQLDatabase;
import de.weapie.devlok.database.utils.BasicDatabase;
import de.weapie.devlok.files.config.DevlokConfig;
import lombok.Getter;
public class Database {
private static DevlokConfig.Builder<DatabaseConfig> databaseConfigBuilder = DevlokConfig
.builder(DatabaseConfig.class)
.withDefault(() ->
new DatabaseConfig(
DatabaseType.MONGODB,
new MySQLAuthenticationModule(
"127.0.0.1",
3306,
"database",
"root",
"password"
), new MongoDBAuthenticationModule(
"127.0.0.1",
27017,
"database",
"root",
"password",
"admin"
)
)
);
private static DevlokConfig<DatabaseConfig> databaseConfig = null;
@Getter
private static BasicDatabase database;
public static void initialize(String path) {
databaseConfig = databaseConfigBuilder
.withPath(path)
.build();
databaseConfig.write();
databaseConfig.read();
switch (databaseConfig.value().getType()) {
case MYSQL -> database = new MySQLDatabase(
databaseConfig.value().getMySQL().getHost(),
databaseConfig.value().getMySQL().getPort(),
databaseConfig.value().getMySQL().getDatabase(),
databaseConfig.value().getMySQL().getUser(),
databaseConfig.value().getMySQL().getPassword()
);
case MONGODB -> database = new MongoDBDatabase(
databaseConfig.value().getMongoDB().getHost(),
databaseConfig.value().getMongoDB().getPort(),
databaseConfig.value().getMongoDB().getDatabase(),
databaseConfig.value().getMongoDB().getUser(),
databaseConfig.value().getMongoDB().getPassword(),
databaseConfig.value().getMongoDB().getAuthDatabase()
);
}
}
public static boolean isInitialized() {
return database != null;
}
}

View File

@ -0,0 +1,22 @@
package de.weapie.devlok.database.config;
import de.weapie.devlok.database.config.module.BasicAuthenticationModule;
import de.weapie.devlok.database.config.module.MongoDBAuthenticationModule;
import de.weapie.devlok.database.config.module.MySQLAuthenticationModule;
import de.weapie.devlok.files.config.annotations.Config;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
@Config(id = "database")
@AllArgsConstructor
@Getter
@Setter
public class DatabaseConfig {
private DatabaseType type;
private MySQLAuthenticationModule mySQL;
private MongoDBAuthenticationModule mongoDB;
}

View File

@ -0,0 +1,6 @@
package de.weapie.devlok.database.config;
public enum DatabaseType {
MYSQL,
MONGODB;
}

View File

@ -0,0 +1,16 @@
package de.weapie.devlok.database.config.module;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public abstract class BasicAuthenticationModule {
private String host;
private int port;
private String database;
private String user;
private String password;
}

View File

@ -0,0 +1,15 @@
package de.weapie.devlok.database.config.module;
import lombok.Getter;
@Getter
public class MongoDBAuthenticationModule extends BasicAuthenticationModule {
private String authDatabase;
public MongoDBAuthenticationModule(String host, int port, String database, String user, String password, String authDatabase) {
super(host, port, database, user, password);
this.authDatabase = authDatabase;
}
}

View File

@ -0,0 +1,12 @@
package de.weapie.devlok.database.config.module;
import lombok.Getter;
@Getter
public class MySQLAuthenticationModule extends BasicAuthenticationModule {
public MySQLAuthenticationModule(String host, int port, String database, String user, String password) {
super(host, port, database, user, password);
}
}

View File

@ -0,0 +1,77 @@
package de.weapie.devlok.database.mongodb;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoDatabase;
import de.weapie.devlok.database.utils.BasicDatabase;
import lombok.Getter;
import org.bson.codecs.configuration.CodecRegistries;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.codecs.pojo.PojoCodecProvider;
import java.util.List;
public class MongoDBDatabase extends BasicDatabase {
@Getter
private MongoClient mongoClient;
@Getter
private MongoDatabase mongoDatabase;
public MongoDBDatabase(String host, int port, String database, String user, String password, String authDatabase) {
super(host, port, database, user, password, authDatabase);
service = new MongoDBService();
}
@Override
public String getDataSourceName() {
return null;
}
@Override
public boolean isConnected() {
return this.mongoClient != null;
}
@Override
public void connect() {
final MongoCredential mongoCredential = MongoCredential.createCredential(
this.user,
this.authDatabase,
this.password.toCharArray()
);
this.mongoClient = new MongoClient(
new ServerAddress(
this.host,
this.port
), List.of(mongoCredential)
);
CodecRegistry pojoCodecRegistry = CodecRegistries.fromRegistries(
MongoClientSettings.getDefaultCodecRegistry(),
CodecRegistries.fromProviders(
PojoCodecProvider.builder()
.automatic(true)
.build()
)
);
this.mongoDatabase = this.mongoClient
.getDatabase(this.database)
.withCodecRegistry(pojoCodecRegistry);
System.out.println("Successfully connected to MongoDB database");
}
@Override
public void disconnect() {
if (!this.isConnected()) return;
this.mongoClient.close();
System.out.println("Successfully disconnected to MongoDB database");
}
}

View File

@ -0,0 +1,144 @@
package de.weapie.devlok.database.mongodb;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.Sorts;
import com.mongodb.client.model.UpdateOptions;
import de.weapie.devlok.database.Database;
import de.weapie.devlok.database.utils.BasicService;
import org.bson.Document;
import java.util.ArrayList;
import java.util.List;
public class MongoDBService implements BasicService {
public MongoDBDatabase database() {
return (MongoDBDatabase) Database.getDatabase();
}
@Override
public MongoCollection<Document> collection(String collection) {
if(!this.database().isConnected()) return null;
return this.database().getMongoDatabase().getCollection(collection);
}
@Deprecated
@Override
public void table(String collection, Document document) {}
@Override
public void insert(String collection, Document document) {
if(!this.database().isConnected()) return;
this.collection(collection).insertOne(document);
}
@Override
public void insertMany(String collection, List<Document> documents) {
if(!this.database().isConnected()) return;
this.collection(collection).insertMany(documents);
}
@Override
public long count(String collection) {
if(!this.database().isConnected()) return 0;
return this.collection(collection).count();
}
@Override
public Document findFirst(String collection) {
if(!this.database().isConnected()) return null;
return this.collection(collection).find().first();
}
@Override
public Document findOne(String collection, Document filter) {
if(!this.database().isConnected()) return null;
return this.collection(collection).find(filter).first();
}
@Override
public List<Document> findMany(String collection, Document filter) {
if(!this.database().isConnected()) return null;
List<Document> documents = new ArrayList<>();
MongoCursor<Document> cursor = this.collection(collection).find(filter).iterator();
try {
while (cursor.hasNext()) {
documents.add(cursor.next());
}
} finally {
cursor.close();
}
return documents;
}
@Override
public List<Document> findAll(String collection) {
if(!this.database().isConnected()) return null;
List<Document> documents = new ArrayList<>();
MongoCursor<Document> cursor = this.collection(collection).find().iterator();
try {
while (cursor.hasNext()) {
documents.add(cursor.next());
}
} finally {
cursor.close();
}
return documents;
}
@Override
public boolean exist(String collection, Document filter) {
if(!this.database().isConnected()) return false;
return this.findOne(collection, filter) != null;
}
@Override
public void update(String collection, Document filter, Document update) {
if(!this.database().isConnected()) return;
this.collection(collection).replaceOne(filter, update);
}
@Override
public void replace(String collection, Document filter, Document replace) {
if(!this.database().isConnected()) return;
this.collection(collection).replaceOne(filter, replace, new UpdateOptions().upsert(true));
}
@Override
public void deleteOne(String collection, Document filter) {
if(!this.database().isConnected()) return;
this.collection(collection).deleteOne(filter);
}
@Override
public void deleteMany(String collection, Document filter) {
if(!this.database().isConnected()) return;
this.findMany(collection, filter).forEach(document -> this.collection(collection).deleteOne(document));
}
@Override
public void deleteAll(String collection) {
if(!this.database().isConnected()) return;
this.findAll(collection).forEach(document -> this.deleteOne(collection, document));
}
@Override
public List<Document> top(String collection, int maxPlace, String fieldName) {
if(!this.database().isConnected()) return null;
List<Document> documents = new ArrayList<>();
for (Document document : this.collection(collection).find().sort(Sorts.descending(fieldName)).limit(maxPlace)) {
documents.add(document);
}
return documents;
}
}

View File

@ -0,0 +1,112 @@
package de.weapie.devlok.database.mysql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import de.weapie.devlok.database.utils.AutoReconnect;
import de.weapie.devlok.database.utils.BasicDatabase;
import lombok.Getter;
public class MySQLDatabase extends BasicDatabase {
@Getter
private Connection connection;
private AutoReconnect autoReconnect;
public MySQLDatabase(String host, int port, String database, String user, String password) {
super(host, port, database, user, password);
service = new MySQLService();
}
@Override
public String getDataSourceName() {
return String.format("jdbc:mysql://%s:%d/%s?useCursorFetch=true", this.host, this.port, this.database);
}
@Override
public boolean isConnected() {
try {
return this.connection != null || this.connection.isValid(1);
} catch (SQLException e) {
return false;
}
}
@Override
public void connect() {
try {
Class.forName("com.mysql.jdbc.Driver");
String dataSourceName = this.getDataSourceName();
this.connection = DriverManager.getConnection(dataSourceName, this.user, this.password);
System.out.println("Successfully connected to MySQL database");
} catch (SQLException | ClassNotFoundException e) {
System.err.println("Unable to connect to MySQL database: " + e.getMessage());
e.printStackTrace();
}
this.autoReconnect = new AutoReconnect();
//this.autoReconnect.start();
}
@Override
public void disconnect() {
this.autoReconnect.interrupt();
try {
if (this.connection != null) {
this.connection.close();
System.out.println("Successfully disconnected to MySQL database");
}
} catch (SQLException e) {
System.err.println("Error while closing the connection: " + e.getMessage());
}
}
public void update(String qry) {
try {
Statement st = this.connection.createStatement();
st.executeUpdate(qry);
st.close();
} catch (SQLException e) {
connect();
System.err.println(e);
}
}
public ResultSet query(PreparedStatement pst) {
ResultSet rs = null;
try {
rs = pst.executeQuery();
rs.close();
} catch (SQLException e) {
System.err.println(e);
}
return rs;
}
}

View File

@ -0,0 +1,227 @@
package de.weapie.devlok.database.mysql;
import com.mongodb.client.MongoCollection;
import de.weapie.devlok.database.Database;
import de.weapie.devlok.database.utils.BasicService;
import org.bson.Document;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
public class MySQLService implements BasicService {
public MySQLDatabase database() {
return (MySQLDatabase) Database.getDatabase();
}
@Deprecated
@Override
public MongoCollection<Document> collection(String collection) { return null; }
@Override
public void table(String collection, Document document) {
if(!this.database().isConnected()) return;
if(!this.executeQuery("SHOW TABLES LIKE '" + collection + "'").isEmpty()) return;
this.execute("CREATE TABLE " + collection + " (" + this.buildString(document, " ", ", ", "") + ");");
}
@Override
public void insert(String collection, Document document) {
if(!this.database().isConnected()) return;
int i = 0;
AtomicReference<String> resultString = new AtomicReference<>("INSERT INTO " + collection + " (");
AtomicReference<String> keyString = new AtomicReference<>("");
AtomicReference<String> valueString = new AtomicReference<>("");
for(String key : document.keySet()) {
Object value = document.get(key);
if(i == document.size() - 1) {
keyString.set(keyString.get() + key);
valueString.set(valueString.get() + "'" + value + "'");
continue;
}
i++;
keyString.set(keyString.get() + key + ", ");
valueString.set(valueString.get() + "'" + value + "', ");
}
resultString.set(resultString.get() + keyString.get() + ") VALUES (");
resultString.set(resultString.get() + valueString.get() + ");");
this.execute(resultString.get());
}
@Override
public void insertMany(String collection, List<Document> documents) {
if(!this.database().isConnected()) return;
documents.forEach(document -> this.insert(collection, document));
}
@Override
public long count(String collection) {
if(!this.database().isConnected()) return 0;
List<Document> documents = this.executeQuery("SELECT COUNT(*) FROM " + collection + ";");
return (long) documents.get(0).get("COUNT(*)");
}
@Override
public Document findFirst(String collection) {
if(!this.database().isConnected()) return null;
List<Document> documents = this.executeQuery("SELECT * FROM " + collection + " LIMIT 1;");
return documents.get(0);
}
@Override
public Document findOne(String collection, Document filter) {
if(!this.database().isConnected()) return null;
List<Document> documents = this.executeQuery("SELECT * FROM " + collection + " WHERE " + this.buildString(filter, " = ", " AND ", "'") + " LIMIT 1;");
return !documents.isEmpty() ? documents.get(0) : null;
}
@Override
public List<Document> findMany(String collection, Document filter) {
if(!this.database().isConnected()) return null;
List<Document> documents = this.executeQuery("SELECT * FROM " + collection + " WHERE " + this.buildString(filter, " = ", " AND ", "'") + ";");
return !documents.isEmpty() ? documents : new ArrayList<>();
}
@Override
public List<Document> findAll(String collection) {
if(!this.database().isConnected()) return null;
List<Document> documents = this.executeQuery("SELECT * FROM " + collection + ";");
return !documents.isEmpty() ? documents : new ArrayList<>();
}
@Override
public boolean exist(String collection, Document filter) {
if(!this.database().isConnected()) return false;
return this.findOne(collection, filter) != null;
}
@Override
public void update(String collection, Document filter, Document update) {
if(!this.database().isConnected()) return;
this.execute("UPDATE " + collection + " SET " + this.buildString(update, " = ", ", ", "'") + " WHERE " + this.buildString(filter, " = ", ", ", "'") + ";");
}
@Override
public void replace(String collection, Document filter, Document replace) {
if(!this.database().isConnected()) return;
this.update(collection, filter, replace);
}
@Override
public void deleteOne(String collection, Document filter) {
if(!this.database().isConnected()) return;
this.execute("DELETE FROM " + collection + " WHERE " + this.buildString(filter, " = ", " AND ", "'") + ";");
}
@Override
public void deleteMany(String collection, Document filter) {
if(!this.database().isConnected()) return;
this.deleteOne(collection, filter);
}
@Override
public void deleteAll(String collection) {
if(!this.database().isConnected()) return;
this.findAll(collection).forEach(document -> this.deleteOne(collection, document));
}
@Override
public List<Document> top(String collection, int maxPlace, String fieldName) {
if(!this.database().isConnected()) return null;
List<Document> documents = this.executeQuery("SELECT * FROM " + collection + " ORDER BY " + fieldName + " DESC LIMIT " + maxPlace + ";");
return !documents.isEmpty() ? documents : new ArrayList<>();
}
private void execute(String sql) {
Statement statement = null;
try {
statement = this.database().getConnection().createStatement();
statement.execute(sql);
} catch (SQLException e) {
e.printStackTrace();
} finally {
if(statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
private List<Document> executeQuery(String sql) {
Statement statement = null;
ResultSet resultSet = null;
try {
statement = this.database().getConnection().createStatement();
resultSet = statement.executeQuery(sql);
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
List<Document> documents = new ArrayList<>();
while(resultSet.next()) {
int i = 1;
boolean bound = true;
Document document = new Document();
while(bound) {
try {
document.append(resultSetMetaData.getColumnName(i), resultSet.getObject(i));
} catch (SQLException ex) {
bound = false;
}
i++;
}
documents.add(document);
}
return documents;
} catch (SQLException e) {
e.printStackTrace();
return null;
} finally {
if(statement != null) {
try {
statement.close();
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
private String buildString(Document document, String separator, String between, String aroundValue) {
int i = 0;
AtomicReference<String> resultString = new AtomicReference<>("");
for(String key : document.keySet()) {
Object value = document.get(key);
if(i == document.size() - 1) {
resultString.set(resultString.get() + key + separator + aroundValue + value + aroundValue);
continue;
}
i++;
resultString.set(resultString.get() + key + separator + aroundValue + value + aroundValue + between);
}
return resultString.get();
}
}

View File

@ -0,0 +1,21 @@
package de.weapie.devlok.database.utils;
import de.weapie.devlok.database.Database;
import lombok.SneakyThrows;
public class AutoReconnect extends Thread {
public AutoReconnect() {
super("autoreconnect");
}
@SneakyThrows
@Override
public void run() {
while(!Database.getDatabase().isConnected()) {
Database.getDatabase().connect();
Thread.sleep(5000);
}
}
}

View File

@ -0,0 +1,45 @@
package de.weapie.devlok.database.utils;
import lombok.Getter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public abstract class BasicDatabase {
protected String host;
protected int port;
protected String database;
protected String user;
protected String password;
protected String authDatabase;
@Getter
protected BasicService service;
@Getter
protected ExecutorService pool;
public BasicDatabase(String host, int port, String database, String user, String password) {
this(host, port, database, user, password, null);
}
public BasicDatabase(String host, int port, String database, String user, String password, String authDatabase) {
this.host = host;
this.port = port;
this.database = database;
this.user = user;
this.password = password;
this.authDatabase = authDatabase;
this.pool = Executors.newCachedThreadPool();
this.connect();
}
public abstract void connect();
public abstract void disconnect();
public abstract boolean isConnected();
public abstract String getDataSourceName();
}

View File

@ -0,0 +1,27 @@
package de.weapie.devlok.database.utils;
import com.mongodb.client.MongoCollection;
import org.bson.Document;
import java.util.List;
public interface BasicService {
MongoCollection<Document> collection(String collection);
void table(String collection, Document document);
void insert(String collection, Document document);
void insertMany(String collection, List<Document> documents);
long count(String collection);
Document findFirst(String collection);
Document findOne(String collection, Document filter);
List<Document> findMany(String collection, Document filter);
List<Document> findAll(String collection);
boolean exist(String collection, Document filter);
void update(String collection, Document filter, Document update);
void replace(String collection, Document filter, Document replace);
void deleteOne(String collection, Document filter);
void deleteMany(String collection, Document filter);
void deleteAll(String collection);
List<Document> top(String collection, int maxPlace, String fieldName);
}

View File

@ -0,0 +1,6 @@
package de.weapie.devlok.database.utils;
public enum Result {
SUCCESS,
FAILURE;
}

View File

@ -0,0 +1,48 @@
package de.weapie.devlok.database.test;
import de.weapie.devlok.database.Database;
import de.weapie.devlok.database.config.DatabaseType;
import de.weapie.devlok.database.mongodb.MongoDBDatabase;
import de.weapie.devlok.database.mysql.MySQLDatabase;
import lombok.SneakyThrows;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.junit.jupiter.api.Test;
import java.util.UUID;
public class TestDatabase {
@SneakyThrows
@Test
public void handle() {
// Initialize & Create connection
Database.initialize("./config/");
// Create table in database
Database.getDatabase().getService().table("players", new Document("uuid", "VARCHAR(100)").append("coins", "INT"));
// Insert entry in database
String uid = UUID.randomUUID().toString();
Database.getDatabase().getService().insert("players", new Document("uuid", uid).append("coins", 0));
System.out.println("Count: " + Database.getDatabase().getService().count("players"));
Document findFirst = Database.getDatabase().getService().findFirst("players");
String uuid = findFirst.getString("uuid");
int coins = findFirst.getInteger("coins");
System.out.println("Exists: " + Database.getDatabase().getService().exist("players", new Document("uuid", uuid)));
// Update entry in database with complete document
Database.getDatabase().getService().replace("players", new Document("uuid", uuid), new Document("uuid", uuid).append("coins", coins + 1));
// Find entry in database
Document document = Database.getDatabase().getService().findOne("players", new Document("uuid", uuid));
System.out.println("Json: " + document.toJson());
// Delete entry from database
Database.getDatabase().getService().deleteOne("players", new Document("uuid", uuid));
}
}

View File

@ -8,6 +8,10 @@ dependencies {
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
tasks.shadowJar {
dependsOn(":devlok-utils:shadowJar")
}
tasks.test {
useJUnitPlatform()
testLogging {

View File

@ -11,6 +11,12 @@ dependencies {
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
tasks.shadowJar {
dependsOn(":devlok-reflections:shadowJar")
dependsOn(":devlok-utils:shadowJar")
dependsOn(":devlok-files:shadowJar")
}
tasks.test {
useJUnitPlatform()
testLogging {

View File

@ -0,0 +1,7 @@
package de.weapie.devlok.redis;
public interface IRedisHandler {
void onHandle(Object object);
}

View File

@ -0,0 +1,34 @@
package de.weapie.devlok.redis;
import de.weapie.devlok.files.config.DevlokConfig;
import de.weapie.devlok.redis.config.RedisConfig;
import de.weapie.devlok.redis.service.RedisService;
import lombok.Getter;
public class Redis {
private static DevlokConfig.Builder<RedisConfig> redisConfigBuilder = DevlokConfig
.builder(RedisConfig.class)
.withDefault(() ->
new RedisConfig(
"127.0.0.1",
6379,
"password"
)
);
private static DevlokConfig<RedisConfig> redisConfig = null;
@Getter
private static RedisService service;
public static void initialize(String path) {
redisConfig = redisConfigBuilder
.withPath(path)
.build();
redisConfig.write();
redisConfig.read();
service = new RedisService(redisConfig.value());
}
}

View File

@ -0,0 +1,22 @@
package de.weapie.devlok.redis;
import redis.clients.jedis.JedisPubSub;
public class RedisHandler extends JedisPubSub {
@Override
public void onMessage(String channel, String message) {
Redis.getService().getRedisMessageChannels().forEach(redisMessageChannel -> {
if(redisMessageChannel.getChannel().equalsIgnoreCase(channel)) {
if(redisMessageChannel.getClazz() == null) {
redisMessageChannel.getHandler().onHandle(null);
return;
}
Object object = Redis.getService().convertClass(message, redisMessageChannel.getClazz());
redisMessageChannel.getHandler().onHandle(object);
}
});
}
}

View File

@ -0,0 +1,14 @@
package de.weapie.devlok.redis;
import lombok.Builder;
import lombok.Getter;
@Getter
@Builder
public class RedisMessageChannel {
private String channel;
private Class<?> clazz;
private IRedisHandler handler;
}

View File

@ -0,0 +1,18 @@
package de.weapie.devlok.redis.config;
import de.weapie.devlok.files.config.annotations.Config;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
@Config(id = "redis")
@AllArgsConstructor
@Getter
@Setter
public class RedisConfig {
private String hostname;
private int port;
private String password;
}

View File

@ -0,0 +1,91 @@
package de.weapie.devlok.redis.service;
import com.google.gson.Gson;
import de.weapie.devlok.redis.RedisMessageChannel;
import de.weapie.devlok.redis.config.RedisConfig;
import lombok.Getter;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPubSub;
import redis.clients.jedis.params.SetParams;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
public class RedisService {
private static final Gson GSON = new Gson();
private static final ScheduledExecutorService SERVICE = Executors.newSingleThreadScheduledExecutor();
private final JedisPool jedisPool;
@Getter
private final List<RedisMessageChannel> redisMessageChannels = new ArrayList<>();
public RedisService(final RedisConfig redisConfig) {
if(redisConfig.getPassword() == null || redisConfig.getPassword().isEmpty()) {
this.jedisPool = new JedisPool(redisConfig.getHostname(), redisConfig.getPort());
return;
}
this.jedisPool = new JedisPool(redisConfig.getHostname(), redisConfig.getPort(), null, redisConfig.getPassword());
}
public void setupSubscriber(JedisPubSub jedisPubSub, String... channel) {
new Thread(() -> {
while (true) {
try (Jedis jedis = this.jedisPool.getResource()) {
jedis.subscribe(jedisPubSub, channel);
}
}
}).start();
}
public void set(String key, Object value, long seconds) {
try (Jedis jedis = this.jedisPool.getResource()) {
jedis.set(key, GSON.toJson(value), SetParams.setParams().ex(seconds));
}
}
public void set(String key, Object value) {
try (Jedis jedis = this.jedisPool.getResource()) {
jedis.set(key, GSON.toJson(value));
}
}
public void del(String key) {
try (Jedis jedis = this.jedisPool.getResource()) {
jedis.del(key);
}
}
public Object get(String key, Class<?> clazz) {
try (Jedis jedis = this.jedisPool.getResource()) {
return GSON.fromJson(jedis.get(key), clazz);
}
}
public Set<String> keys(String pattern) {
try (Jedis jedis = this.jedisPool.getResource()) {
return jedis.keys(pattern);
}
}
public void registerChannel(RedisMessageChannel redisMessageChannel) {
this.redisMessageChannels.add(redisMessageChannel);
}
public void send(String channel, Object object) {
try (Jedis jedis = this.jedisPool.getResource()) {
jedis.publish(channel, GSON.toJson(object));
}
}
public Object convertClass(String message, Class<?> clazz) {
return GSON.fromJson(message, clazz);
}
}

View File

@ -0,0 +1,14 @@
package de.weapie.devlok.redis.test;
import de.weapie.devlok.redis.Redis;
import org.junit.jupiter.api.Test;
public class RedisTest {
@Test
public void handle() {
Redis.initialize("./config/");
Redis.getService().send("test", "Test-Message");
}
}

View File

@ -1,19 +1,19 @@
[versions]
annotations = "24.1.0"
lombok = "1.18.32"
gson = "2.11.0"
#networking
netty5 = "5.0.0.Alpha5"
mongodb = "3.12.14"
mysql = "5.1.36"
redis = "4.2.0"
[libraries]
lombok = { group = "org.projectlombok", name="lombok", version.ref = "lombok" }
annotations = { group = "org.jetbrains", name="annotations", version.ref = "annotations" }
gson = { group = "com.google.code.gson", name="gson", version.ref = "gson" }
#networking
netty5 = { group = "io.netty", name = "netty5-all", version.ref = "netty5" }
mongodb = { group = "org.mongodb", name = "mongodb-driver", version.ref = "mongodb" }
mysql = { group = "mysql", name = "mysql-connector-java", version.ref = "mysql" }
redis = { group = "redis.clients", name = "jedis", version.ref = "redis" }
[plugins]

View File

@ -4,3 +4,5 @@ include("devlok-utils")
include("devlok-reflections")
include("devlok-files")
include("devlok-netty")
include("devlok-databases")
include("devlok-redis")