What is Redis ?
Redis is an open-source, in-memory NoSQL key-value store primarily used for caching, session storage, and message brokering. It stores data in RAM, which enables extremely fast read and write operations compared to traditional disk-based databases
Here's a more detailed breakdown:
In-memory Data Store:
Redis stores data in memory, making it significantly faster than disk-based databases.
NoSQL Key-Value Store:
Redis is a NoSQL database, meaning it doesn't adhere to the traditional relational database model. It uses a key-value pair structure, where each key maps to a value.
Caching:
Redis is commonly used as a cache to speed up applications by storing frequently accessed data in memory.
Session Storage:
It can store user session data, providing a fast and efficient way to manage sessions in web applications.
Message Broker:
Redis can also act as a message broker, allowing different parts of an application to communicate with each other.
Data Types:
Redis supports various data types, including strings, lists, sets, streams, and hashes, allowing for a wide range of data storage and manipulation.
Open Source and Enterprise Versions:
Redis is available as an open-source project and also has a commercial version (Redis Enterprise) that offers additional features and supports.
Let's go to create new project spring boot.
Configuration Redis in Spring Boot Application
package com.example.redislearn.settings;
import com.example.redislearn.product.dto.ProductDto;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import java.time.Duration;
@Configuration // Marks this class as a Spring configuration class
public class RedisConfig {
@Bean // Defines a Spring bean for RedisCacheManager
public RedisCacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory) {
// Define cache configuration
RedisCacheConfiguration cacheConfig = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10)) // Set time-to-live (TTL) for cache entries to 10 minutes
.disableCachingNullValues() // Prevent caching of null values
.serializeValuesWith(RedisSerializationContext.SerializationPair
.fromSerializer(new Jackson2JsonRedisSerializer<>(ProductDto.class))); // Serialize values using Jackson JSON serializer
// Create and return a RedisCacheManager with the specified configuration
return RedisCacheManager.builder(redisConnectionFactory)
.cacheDefaults(cacheConfig) // Apply default cache configuration
.build();
}
}
Services
package com.example.redislearn.product.services;
import com.example.redislearn.product.dto.ProductDto;
import com.example.redislearn.product.entity.Product;
import com.example.redislearn.product.repository.ProductRepository;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class ProductService {
private final ProductRepository productRepository;
public ProductService(ProductRepository productRepository) {
this.productRepository = productRepository;
}
@CachePut(value="PRODUCT_CACHE", key="#result.id")
public ProductDto createProduct(ProductDto productDto) {
var product = new Product();
product.setName(productDto.name());
product.setPrice(productDto.price());
Product savedProduct = productRepository.save(product);
return new ProductDto(savedProduct.getId(), savedProduct.getName(),
savedProduct.getPrice());
}
@Cacheable(value="PRODUCT_CACHE", key="#productId")
public ProductDto getProduct(Long productId) {
Product product = productRepository.findById(productId)
.orElseThrow(() -> new IllegalArgumentException("Cannot find product with id " + productId));
return new ProductDto(product.getId(), product.getName(),
product.getPrice());
}
@CachePut(value="PRODUCT_CACHE", key="#result.id")
public ProductDto updateProduct(ProductDto productDto) {
Long productId = productDto.id();
Product product = productRepository.findById(productId)
.orElseThrow(() -> new IllegalArgumentException("Cannot find product with id " + productId));
product.setName(productDto.name());
product.setPrice(productDto.price());
Product updatedProduct = productRepository.save(product);
return new ProductDto(updatedProduct.getId(), updatedProduct.getName(),
updatedProduct.getPrice());
}
@CacheEvict(value="PRODUCT_CACHE", key="#productId")
public void deleteProduct(Long productId) {
productRepository.deleteById(productId);
}
}
Top comments (0)