Monday, May 21, 2018

Implementing Redis with Spring boot


Redis is one of the most used inmemory cache server used in most of the distributed system for saving the key value data structures in memory for defined time interval along with some other features like pub sub and more.


So In this article you will learn how to use redis server and store the data in it while working on spring boot.


So lets start (You can Download the project from github
First we will create simple spring boot project 

Adding Dependency

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>

 <groupId>com.programinjava.learn</groupId>
 <artifactId>RedisWithSpringBoot</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>jar</packaging>

 <name>RedisWithSpringBoot</name>
 <description>Demo project for Spring Boot</description>

 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.0.2.RELEASE</version>
  <relativePath /> <!-- lookup parent from repository -->
 </parent>

 <properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  <java.version>1.8</java.version>
 </properties>

 <dependencies>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-redis</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
   <groupId>redis.clients</groupId>
   <artifactId>jedis</artifactId>
   <type>jar</type>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
  </dependency>
 </dependencies>

 <build>
  <plugins>
   <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
   </plugin>
  </plugins>
 </build>


</project>
In pom.xml you will see there are 2 dependency for redis ,

                <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-redis</artifactId>
  </dependency>
                <dependency>
   <groupId>redis.clients</groupId>
   <artifactId>jedis</artifactId>
   <type>jar</type>
  </dependency>
After that you need to define configurations



RedisConfigurations.java

package com.programinjava.learn.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

import com.programinjava.learn.model.User;

@Configuration
public class RedisConfigurations {
 
 
 @Bean
 public JedisConnectionFactory jedisConnectionFactory() {
  JedisConnectionFactory jedisConFactory
       = new JedisConnectionFactory();
     jedisConFactory.setHostName("localhost");
     jedisConFactory.setPort(6379);
     return jedisConFactory;
 }
 
 @Bean
 public RedisTemplate<String, User> redisTemplate(){
  RedisTemplate<String,User> redisTempate = new RedisTemplate<>();
  redisTempate.setConnectionFactory(jedisConnectionFactory());
  return redisTempate;
 }
 

}
In above Configuration we have defined 2 beans
JedisConfigurationFactory : it will show where the redis server is running and where it need to connect with the server.

RedisTemplate: is to do execution and do crud operation for redis .

Adding Repository

@Repository
public interface UserRespository extends CrudRepository<User, Integer> {


}

User Model Class 

package com.programinjava.learn.model;

import java.io.Serializable;

import org.springframework.data.redis.core.RedisHash;

@RedisHash("User")
public class User implements Serializable{
 
 private Integer id;
 private String name;
 private Integer age;
 
 public Integer getId() {
  return id;
 }
 public void setId(Integer id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public Integer getAge() {
  return age;
 }
 public void setAge(Integer age) {
  this.age = age;
 }
 
 
 

}

Now we will add Service class



UserService.java

package com.programinjava.learn.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.programinjava.learn.model.User;
//import com.programinjava.learn.repository.UserRespositoryImpl;
import com.programinjava.learn.repository.UserRespository;

@Service
public class UserService {
 
 
 @Autowired
 UserRespository userRespository;
 
 public void saveUser(User user) {
  userRespository.save(user);
 }
 
 
 

}

After this we will see the Controller file
UserController.java

package com.programinjava.learn.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.programinjava.learn.model.User;
import com.programinjava.learn.service.UserService;

@Controller
public class UserController {
 
 @Autowired
 UserService userService;
 
 
 @PostMapping("/userprocess")
 public String saveUser(@ModelAttribute User user ,ModelMap map) {
  
  userService.saveUser(user); 
  map.addAttribute("message", "Successfully Added User");
  return "index";
  
 }
 
 @GetMapping("/user")
 public String getIndex(ModelMap map) {
  map.addAttribute("user",new User());
  return "index";
 }
 
 

}

Till now we have added all the files but to create user and store it in redis server , we have created one index.html
in this we are using thymeleaf template enginer.
let see index.html

<!DOCTYPE html>

<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>Index</title>
</head>
<body>
<form action="/userprocess" th:object="${user}" method="post">

<input type="text" th:field="*{name}" placeholder="Enter your name"></input>
<input type="number" th:field="*{age}" placeholder="Enter your age"></input>

<br/>
<input type="submit"/>
</form>

<span th:if=${message}>
 <h2 th:text="${message}"></h2>
</span>
</body>
</html>

Thats it
After deploy it and start redis server we will hit the URL
http://localhost:8080/userprocess


After that when we see the redis console , we will be able to see it like below image

Hope this will help you in implementing redis with spring boot

Read Also
  1. Spring Boot and Hibernate Tutorials - Application using Spring Boot
  2. What is Spring boot ?
  3. How to read value from property file in spring boot ?
  4. First Rest API Application - Top Spring Framework Interview Questions
  5. File Uploading in Spring MVC using thymeleaf and spring boot
Thanks for reading

0 comments:

Post a Comment