Learning Redis Basic Data Structure and Mapping With Java Data Structure
In this article, we will demonstrate the usage of java data structure with its corresponding Redis data type in terms of java code as a Jedis client.
Join the DZone community and get the full member experience.
Join For FreeWe all know that Redis is an in-memory database server which has its own data structure.
String(float and integer) |
512MB; Stores string, numerical value, serialized JSON, and binary |
list |
Stores list of Strings and holds 4 billion entries. It is used to design Queue and Stack. It is implemented as a doubly LinkedList. |
set |
Allows the unique collection of elements. Supports set operations like difference, intersect, and union. |
hash |
Collection of field-value pairs and mutable. |
The below table is the corresponding java data structure.
String |
String stores sequence of characters. |
List<String> |
Stores list of Strings and holds 4 billion entries. It is used to design Queue and Stack. It is implemented as a doubly LinkedList. |
Set<String> |
Allows the unique collection of elements. Supports set operations like difference, intersect, and union. |
Map<String, String> |
Collection of field-value pairs and mutable. |
Double |
Primitive data type |
Long |
Primitive data type |
Prerequisites
- Eclipse (any version) with Maven capabilities
- Java 8+
- Junit
- Redis and Jedis
Installing Redis Server on Windows
- Click on the link: https://github.com/dmajkic/redis/downloads
- Download redis-2.4.5-win32-win64.zip file
- Unzip the file and go to 64bit folder. There you can find redis-server.exe
- To start the Redis server, execute the redis-server.exe file.
Installing Eclipse-IDE on Windows
- Click on the link: https://www.eclipse.org/downloads/download.php?file=/oomph/epp/2020-09/R/eclipse-inst-jre-win64.exe
- Download eclipse-inst-jre-win64.exe file and run the eclipse installer.
3.Select Eclipse IDE for Eclipse committers and install
Creating a Maven Project in Eclipse IDE
- Open the Eclipse IDE
2.Go to File > New > Project
3.Go to Maven -> Maven Project and click Next.
4.Select your workspace location and click Next
5.Select quick start maven archetype and click Next.
6.Enter Group Id, Artifact Id, and package name.
- Group Id: Fill a groupId for the project of your choice.
- Artifact Id: Fill artifactId for the project of your choice.
- Package: java package structure of your choice
7.The above process will create a project structure like below.
8. Place the HostPort.java file in com.example.demo package.
package com.example.demo;
public class HostPort {
final private static String defaultHost = "localhost";
final private static Integer defaultPort = 6379;
final private static String defaultPassword = "";
public static String getRedisHost() {
return defaultHost;
}
public static Integer getRedisPort() {
return defaultPort;
}
public static String getRedisPassword() {
return defaultPassword;
}
}
9. Add the JedisBasicsTest.java file in com.example.demo package.
xxxxxxxxxx
package com.example.demo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import redis.clients.jedis.Jedis;
public class JedisBasicsTest {
public static String[] testPlanets = { "Mercury", "Mercury", "Venus", "Earth", "Earth", "Mars", "Jupiter", "Saturn",
"Uranus", "Neptune", "Pluto" };
private Jedis;
public void setUp() {
this.jedis = new Jedis(HostPort.getRedisHost(), HostPort.getRedisPort());
if (HostPort.getRedisPassword().length() > 0) {
jedis.auth(HostPort.getRedisPassword());
}
jedis.del("planets");
jedis.del("earth");
}
public void tearDown() {
jedis.del("planets");
jedis.del("earth");
jedis.close();
}
public void testRedisList() {
assertThat(testPlanets.length, is(11));
/* Add all test planets to the Redis set */
for (String testPlanet : testPlanets) {
Long result=jedis.rpush("planets", testPlanet);
//System.out.println(result);
}
// Check the length of the list
Long length = jedis.llen("planets");
System.out.println(length);
assertThat(length, is(11L));
// Get the planets from the list
// Note: LRANGE is an O(n) command. Be careful running this command
// with high-cardinality sets.
List<String> planets = jedis.lrange("planets", 0, -1);
System.out.println(planets);
assertThat(planets, is(Arrays.asList(testPlanets)));
// Remove the elements that we know are duplicates
jedis.lrem("planets", 1, "Mercury");
jedis.lrem("planets", 1, "Earth");
// Drop a planet from the end of the list
String planet = jedis.rpop("planets");
assertThat(planet, is("Pluto"));
length = jedis.llen("planets");
System.out.println(length);
assertThat(length, is(8L));
}
public void testRedisSet() {
assertThat(testPlanets.length, is(11));
// Add all test planets to the Redis set
jedis.sadd("planets", testPlanets);
// Return the cardinality of the set
Long length = jedis.scard("planets");
System.out.println("length :: "+length);
assertThat(length, is(9L));
// Fetch all values from the set
// Note: SMEMBERS is an O(n) command. Be careful running this command
// with high-cardinality sets. Consider SSCAN as an alternative.
Set<String> planets = jedis.smembers("planets");
System.out.println("planets :: "+planets);
// Ensure that a HashSet created and stored in Java memory and the set stored
// in Redis have the same values.
Set<String> planetSet = new HashSet<>(Arrays.asList(testPlanets));
assertThat(planets, is(planetSet));
// Pluto is, of course, no longer a first-class planet. Remove it.
Long response = jedis.srem("planets", "Pluto");
assertThat(response, is(1L));
// Now we have 8 planets, as expected.
Long newLength = jedis.scard("planets");
System.out.println("newLength :: "+newLength);
assertThat(newLength, is(8L));
}
public void testRedisHash() {
Map<String, String> earthProperties = new HashMap<>();
earthProperties.put("diameterKM", "12756");
earthProperties.put("dayLengthHrs", "24");
earthProperties.put("meanTempC", "15");
earthProperties.put("moonCount", "1");
// Set the fields of the hash one by one.
for (Map.Entry<String, String> property : earthProperties.entrySet()) {
jedis.hset("earth", property.getKey(), property.getValue());
}
// Get the hash we just created back from Redis.
Map<String, String> storedProperties = jedis.hgetAll("earth");
System.out.println("storedProperties :: "+storedProperties);
assertThat(storedProperties, is(earthProperties));
// Setting fields all at once is more efficient.
jedis.hmset("earth", earthProperties);
storedProperties = jedis.hgetAll("earth");
System.out.println("storedProperties :: "+storedProperties);
assertThat(storedProperties, is(earthProperties));
// Test that we can get a single property.
String diameter = jedis.hget("earth", "diameterKM");
System.out.println("diameter :: "+diameter);
assertThat(diameter, is(earthProperties.get("diameterKM")));
}
}
10.Replace the pom.xml with the below content.
xxxxxxxxxx
<project
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<prerequisites>
<maven>3.0.0</maven>
</prerequisites>
<groupId>RedisDataStructDemo</groupId>
<artifactId>RedisDataStructDemo</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>RedisDataStructDemo</name>
<properties>
<redis.host>localhost</redis.host>
<redis.port>6379</redis.port>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<dropwizard.version>1.3.8</dropwizard.version>
<mainClass>com.example.demo.RediSolarApplication</mainClass>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-bom</artifactId>
<version>${dropwizard.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
<version>4.2.2</version>
</dependency>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-core</artifactId>
</dependency>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-assets</artifactId>
</dependency>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-testing</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.1.0-m3</version>
</dependency>
<dependency>
<groupId>com.redislabs</groupId>
<artifactId>jredistimeseries</artifactId>
<version>0.9.0</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.2.11</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.2.11</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.2.11</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.0.0</version>
<executions>
<execution>
<phase>initialize</phase>
<goals>
<goal>read-project-properties</goal>
</goals>
<configuration>
<files>
<file>pom.xml</file>
</files>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-shade-plugin</artifactId>
<version>2.4.1</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>${mainClass}</mainClass>
</transformer>
</transformers>
<!-- exclude signed Manifests -->
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>${mainClass}</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-source-plugin</artifactId>
<version>3.0.1</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<plugin>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>2.8.1</version>
<configuration>
<dependencyLocationsEnabled>false</dependencyLocationsEnabled>
<dependencyDetailsEnabled>false</dependencyDetailsEnabled>
</configuration>
</plugin>
<plugin>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.10.3</version>
</plugin>
</plugins>
</reporting>
</project>
Running the Code
1.Build the Maven project and run the test case as shown below
2.Check the test result.
Now, we learned Redis' basic data structure and working with the Jedis java API.
Further, this use case can be adapted according to your requirements.
Feel free to ask any questions.
Opinions expressed by DZone contributors are their own.
Comments