Spring Boot With Redis Without Database

What is Redis?

Redis stands for Remote Dictionary Server. It is an open source NoSQL database. It doesn’t have any tables, rows and columns. Also, it doesn’t allow statements like select statement, insert statements, update statements etc.

It stores objects using key/value and basically used to cache and quick-response in an application to speed or increase performance.

Various ways of Redis

  1. In-Memory Database
  2. Cache

In-Memory Database

In-Memory Database(IMDS) enables minimal response times. It provides responses in microsecond of times. It is the good choice for the application if an application handles the large numbers of traffic.

Advantages:

  1. Low latency - provides real time responses
  2. High throughput
  3. High scalability

Cache

The cache provides data quickly with high latency to increase the data retrieval performance. Redis is the good choice for caching API calls, session states, and database queries etc.

Advantages:

  1. High latency - provides data quickly and increase performance.
  2. Faster access to cached data.
  3. Response time is faster because data is retrieved from memory.

How Redis Works?

When a request comes, the code of logic checks in the Redis cache for the desired data. If appropriate data is available in the redis cache, logic simply returns the data from redis cache.

If the requested data is not available/found in the redis cache, the logic falls back to the database or original data source to retrieve the required information to return required data. Subsequently, the fetched data is stored in the Redis cache.

Spring Boot with Redis Configuration

  1. First, you need to run redis on your local machine.
  2. - Create a docker-compose.yaml file in the root directory in your application.
    - Copy the below code and paste into docker-compose.yaml.
    - Open command prompt and go to the directory where you have created docker-compose.yaml file.
    - Run command as docker compose up in the command prompt.

    docker-compose.yaml file
    version: '3.7'
    services:
        redis:
        image: redis
        volumes:
        - ./data:/data
        ports:
        - "6379:6379"
  3. Below dependencies are required in spring boot application.
  4.     
    <dependency>
      <groupId> org.springframework.boot </groupId>
      <artifactId> spring-boot-starter-data-redis </artifactId>
    </dependency>
    
    <dependency>
        <groupId> org.springframework.boot </groupId>
        <artifactId> spring-boot-starter-cache </artifactId>
    </dependency>
    
    

  5. Need to add @EnableCaching annotation in the main class. Also create bean of cacheConfiguration as per below example.
  6. import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cache.annotation.EnableCaching;
    import org.springframework.context.annotation.Bean;
    import org.springframework.data.redis.cache.RedisCacheConfiguration;
    import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
    import org.springframework.data.redis.serializer.RedisSerializationContext;
    import java.time.Duration;
        
    @SpringBootApplication
    @EnableCaching // Annotation need to declare
    public class SpringBootMainApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(SpringBootMainApplication.class, args);
        }
    
        //Need to add below bean
        @Bean
        public RedisCacheConfiguration cacheConfiguration() {
            return RedisCacheConfiguration
                    .defaultCacheConfig()
                    //Cache Expiry time
                    .entryTtl(Duration.ofMinutes(60))
                    .serializeValuesWith(RedisSerializationContext
                            .SerializationPair
                            .fromSerializer( new GenericJackson2JsonRedisSerializer() ));
        }
    }
    

  7. Create POJO class
  8. import java.io.Serializable;
    
        @Data
        @NoArgsConstructor
        @AllArgsConstructor
        public class Book implements Serializable {
        
            private Integer bookId;
            private String bookName;
        
        }
    

  9. Create Service class
  10. import com.entity.Book;
    import org.springframework.cache.annotation.CacheConfig;
    import org.springframework.cache.annotation.CacheEvict;
    import org.springframework.cache.annotation.CachePut;
    import org.springframework.cache.annotation.Cacheable;
    import org.springframework.stereotype.Service;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Optional;
    
    @Service
    @CacheConfig(cacheNames = "book")
    public class BookService {
    
        private static List bookList=new ArrayList();
        static{
            bookList.add(new Book(1, "Sample Book1"));
            bookList.add(new Book(2, "Sample Book2"));
            bookList.add(new Book(3, "Sample Book3"));
            bookList.add(new Book(4, "Sample Book4"));
            bookList.add(new Book(5, "Sample Book5"));
            bookList.add(new Book(6, "Sample Book6"));
        }
    
        @Cacheable(value = "Book", key = "#id", condition="#id!=null")
        public Book findById(Integer id) {
            System.out.println("Fetching book");
            return getBookbyId(id);
        }
    
        @CachePut(cacheNames = "Book", key = "#id")
        public void updateBook(Book post) {
            // updatebook();
        }
        @CacheEvict(cacheNames = "Book", key = "#id", beforeInvocation = true)
        public void deleteById(Integer bookId) {
            // delete book
        }
    
        private Book getBookbyId(Integer bookId){
            System.out.println("Finding book");
            Optional book = bookList
                        .stream()
                        .filter(b -> b.getBookId()==bookId)
                    .findFirst();
    
            return book.get();
        }
    }
     

  11. Create Controller class
  12. import com.entity.Book;
    import com.inventory.service.impl.BookService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.*;
    
    @RestController
    @RequestMapping(path="/api")
    
    public class BookController {
    
        @Autowired
        BookService service;
    
        @GetMapping("/books/{id}")
        public @ResponseBody Book findById(@PathVariable("id") Integer postId) {
            return service.findById(postId);
        }
    
        @PostMapping("/updatepost")
        public void updatePost(Book post) {
            service.updateBook(post);
        }
    
        @DeleteMapping("/posts/{id}")
        public void deleteById(@PathVariable("id") Integer postId) {
            service.deleteById(postId);
        }
    }
     

  13. Cache Testing with POSTMAN
  14. Start the Spring Boot Application and hit the GET URL on POSTMAN. You can see that "Finding book" will be prited once time only if you hit the URL multiple times with the same ID.
    The cached will be removed automatically after 60 minutes as the ttl time is configured with 60 minutes in the bean of cacheConfiguration.

    Spring Boot Redis In Java