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

Progressive Web Apps

Deliver amazing user experience for WEB
Introduction
Progressive Web Apps (PWA) are user experience that reach for web. Its useful to users from the very first visit with no installation required. As the user spends more time with the web app it becomes more and more powerful, It loads quickly even on slower networks. Can have offline support, push notification, icon on home screen, full screen support. PWA are:
Reliable - load instantly even on slower/uncertain network.Fast - Respond quickly to user interactionsEngaging - Feel like natural app on device with amazing user experience.Reliable When launched from the user’s home screen, service workers enable a Progressive Web App to load instantly, regardless of the network state. A service worker, written in JavaScript, is like a client-side proxy and puts you in control of the cache and how to respond to resource requests. By pre-caching key resources you can eliminate the dependence on the network, ensuring an instant and reliable ex…

Zuul Edge Server

Zuul to Proxy your Microservices A common challenge when building microservices is providing a unified interface to the consumers of your system. The fact that your services are split into small composableappsshouldn’t be visible to users or result in substantial development effort. To solve this problem, Netflix created and open-sourced its Zuulproxy server. Zuul is an edge service that proxies requests to multiple backing services. It is “front door” to your system, which allows a browser, mobile app, or other user interface to consume services from multiple hosts without managing cross-origin resource sharing (CORS) and authentication for each one. Spring Cloud has created an embedded Zuul proxy to ease the development of a very common use case where a UI application wants to proxy calls to one or more back end services. This feature is useful for a user interface to proxy to the backend services it requires, avoiding the need to manage CORS and authentication concerns independentl…