Skip to main content

Redis Basic CRUD

We have seen how to setup on your linux machine here , now we will see how to perform basic CRUD operations using Spring Data & Redis server

We will be creating a simple application that would persist an employee information into redis database. You will be needing certain JARs like jedis.jar, spring-data-redis.jar etc details of which you can download and view at https://github.com/meta-magic/RedisCRUDexample.git 
First of all we will be creating the Employee entity, plz note that we are using the Serializable interface which automatically mapps the objects against the key.


Employee.java



import java.io.Serializable;
public class Employee implements Serializable
{
private static final long serialVersionUID = -8243145429438016231L;
public enum Gender{Male, Female}
private String id;
private String name;
private Gender gender;
private int age;
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Gender getGender()
{
return gender;
}
public void setGender(Gender gender)
{
this.gender = gender;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
...
}

Then, we will be defining the Repository interface and its implementation

EmployeeRepository.java
import java.util.Map;
import com.metamagicglobal.examples.redis.entity.Employees;
public interface EmployeeRepository
{
public void addEmployee(Employees employee);
public Employees getEmployeeById(String id);
public Map<Object, Object> getAllEmployees();
void updateEmployee(Employees employee);
public void delEmployeeById(String id);
}
EmployeeRepositoryImpl uses the RedisTemplate to communicate with the Redis Server. Since we are using Hash based Operations, we are using the Redistemplate opsForHash(). The method returns an instance of HashOperations class


EmployeeRepositoryImpl.java

public class EmployeeRepositoryImpl implements EmployeeRepository
{
private RedisTemplate<String, Employees> redisTemplate;
private static String EMP_KEY = "Employees";
public RedisTemplate<String, Employees> getRedisTemplate()
{
return redisTemplate;
}
public void setRedisTemplate(RedisTemplate<String, Employees> redisTemplate)
{
this.redisTemplate = redisTemplate;
}
@Override
public void addEmployee(Employees emp)
{
this.redisTemplate.opsForHash().put(EMP_KEY, emp.getId(), emp);
}
@Override
public Employees getEmployeeById(String id)
{
return (Employees)this.redisTemplate.opsForHash().get(EMP_KEY, id);
}
@Override
public Map<Object,Object> getAllEmployees()
{
return this.redisTemplate.opsForHash().entries(EMP_KEY);
}
@Override
public void delEmployeeById(String id)
{
this.redisTemplate.opsForHash().delete(EMP_KEY,id);
}
@Override
public void updateEmployee(Employees emp) {
// TODO Auto-generated method stub
this.redisTemplate.opsForHash().put(EMP_KEY, emp.getId(), emp);
}
}
The RedisTemplate injected into the EmployeeRepositoryImpl class by the Spring BeanFactory. The RedisTemplate requires the JedisConnectionFactory instance from the Jedis JAR. Next we inject the RedisTemplate instance into the EmployeeRepositoryImpl bean as a reference. We can also use @Autowired to configure the same and add the component-scan directive in the XML.

spring-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- Redis Connection Factory -->
<bean id="jedisConnFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:use-pool="true" />
<!-- Redis Template Configuration-->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
p:connection-factory-ref="jedisConnFactory" />
<bean id="empRepo" class="com.metamagicglobal.examples.redis.repository.EmployeeRepositoryImpl">
<property name="redisTemplate" ref="redisTemplate" />
</bean>
</beans>



We shall test the code using the repository calls on employee object.

EmployeeTest.java


public class EmployeeTest {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
new ClassPathResource("resources/spring-config.xml").getPath());
EmployeeRepository empRepo = (EmployeeRepository) context.getBean("empRepo");
Employees emp = new Employees();
emp.setId("101");
emp.setAge(55);
emp.setGender(Gender.Female);
emp.setName("Jenny Joe");
empRepo.addEmployee(emp);
...
Map<Object, Object> empMap = empRepo.getAllEmployees();
System.out.println("Display All Employees");
System.out.println(empMap);
System.out.println("Find Employee by ID : " + empRepo.getEmployeeById("103"));
emp3.setAge(40);
empRepo.updateEmployee(emp3);
System.out.println("Employee after update : " + empRepo.getEmployeeById("103"));
System.out.println("Deleting Employee ID : 102 ");
empRepo.delEmployeeById("102");
System.out.println("Display All Employees");
empMap = empRepo.getAllEmployees();
System.out.println(empMap);
context.close();
}
}

Output

Display All Employees

{103=
Employee - ID=103, Name=Ken Peg, Gender=Male, Age=25, 102=
Employee - ID=102, Name=John Doe, Gender=Male, Age=60, 101=
Employee - ID=101, Name=Jenny Joe, Gender=Female, Age=55}
Find Employee by ID  : 
Employee - ID=103, Name=Ken Peg, Gender=Male, Age=25
Employee after update  : 
Employee - ID=103, Name=Ken Peg, Gender=Male, Age=40
Deleting Employee ID : 2 
Display All Employees
{103=
Employee - ID=103, Name=Ken Peg, Gender=Male, Age=40, 101=

Employee - ID=101, Name=Jenny Joe, Gender=Female, Age=55}

Comments

Popular posts from this blog

Centralized configuration using Spring Cloud Config

In this blog we will be focusing on centralized configuration using  Spring Cloud Config  project. For single standalone application we can keep all required configuration bundle with application itself.  However, when we have more than one application, say in a microservice architecture, a better alternative would be to manage the configurations centrally. With the Config Server we have a central place to manage external properties for applications with support for different environments. Configuration files in several formats like YAML or properties are added to a Git repository. Features Spring Cloud Config Server features: HTTP, resource-based API for external configuration (name-value pairs, or equivalent YAML content) Encrypt and decrypt property values (symmetric or asymmetric) Embeddable easily in a Spring Boot application using  @EnableConfigServer Config Client features (for Spring applications): Bind to the Config Server and initialize...

Eureka-Server with spring cloud netflix

In this write-up we will focus on Service Registry – Eureka Server Rest service (auth-service application, eureka client) which register itself to registry. Web application which consumes Rest service using service registry. Service discovery  allows services to find and communicate with each other without hardcoding hostname and port. Eureka Server In spring-boot application enable the Eureka-Server by adding @EnableEurekaServer annotation to spring boot application. We have put all the configuration on GIT and this is accessed using config-server. To now more about centralized configuration (config-server) click  here eurekaserver.yml Place below bootstrap.yml in application, it basically connects to config-server and gets it required configuration. Start the spring-boot application and access eureka server using http://localhost:8760/ you will get below screen. Right now there is no application which...