Skip to main content

Command Palette

Search for a command to run...

Bài 16: Spring Boot với Redis

Published
4 min readView as Markdown

1. Giới thiệu về Redis

Redis là một cơ sở dữ liệu NoSQL dạng key-value lưu trữ dữ liệu trong bộ nhớ, cung cấp hiệu suất cao và độ trễ thấp. Redis hỗ trợ nhiều cấu trúc dữ liệu như strings, hashes, lists, sets, sorted sets, bitmaps, hyperloglogs, và geospatial indexes.

2. Lợi ích của Redis

  • Hiệu suất cao: Dữ liệu được lưu trữ trong bộ nhớ, cho phép truy xuất nhanh chóng.

  • Đa dạng cấu trúc dữ liệu: Hỗ trợ nhiều cấu trúc dữ liệu phong phú.

  • Khả năng mở rộng: Có thể mở rộng dễ dàng theo chiều ngang.

  • Độ tin cậy cao: Hỗ trợ tính năng sao lưu và khôi phục dữ liệu.

3. Cách tích hợp Redis vào dự án Spring Boot

3.1. Thêm dependency

Đầu tiên, bạn cần thêm các dependency cần thiết vào dự án của mình. Chúng ta sẽ sử dụng spring-boot-starter-data-redis.

Ví dụ với Maven:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

Ví dụ với Gradle:

implementation 'org.springframework.boot:spring-boot-starter-data-redis'

3.2. Cấu hình Redis

Bạn cần cấu hình kết nối đến Redis trong file application.properties.

spring.redis.host=localhost
spring.redis.port=6379

3.3. Sử dụng RedisTemplate

Spring Boot cung cấp RedisTemplate để tương tác với Redis. Dưới đây là ví dụ về cách sử dụng RedisTemplate để lưu trữ và truy xuất dữ liệu từ Redis.

Tạo một cấu hình Redis

// RedisConfig.java
package com.example.myapp.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        return template;
    }
}

Sử dụng RedisTemplate trong Service

// UserService.java
package com.example.myapp.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static final String USER_KEY = "USER";

    public void saveUser(User user) {
        redisTemplate.opsForHash().put(USER_KEY, user.getId().toString(), user);
    }

    public User getUser(String userId) {
        return (User) redisTemplate.opsForHash().get(USER_KEY, userId);
    }

    public List<Object> getAllUsers() {
        return redisTemplate.opsForHash().values(USER_KEY);
    }

    public void deleteUser(String userId) {
        redisTemplate.opsForHash().delete(USER_KEY, userId);
    }
}

4. Ví dụ chi tiết

Dưới đây là một ví dụ chi tiết từ đầu đến cuối về việc sử dụng Redis trong ứng dụng Spring Boot.

4.1. Tạo dự án Spring Boot

Sử dụng Spring Initializr để tạo dự án với các dependency sau:

  • Spring Web

  • Spring Data Redis

4.2. Cấu hình application.properties

spring.redis.host=localhost
spring.redis.port=6379

4.3. Tạo Entity User

// User.java
package com.example.myapp.entity;

import java.io.Serializable;

public class User implements Serializable {
    private String id;
    private String name;
    private String email;

    // getters and setters
}

4.4. Tạo cấu hình Redis

// RedisConfig.java
package com.example.myapp.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        return template;
    }
}

4.5. Tạo Service UserService

// UserService.java
package com.example.myapp.service;

import com.example.myapp.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static final String USER_KEY = "USER";

    public void saveUser(User user) {
        redisTemplate.opsForHash().put(USER_KEY, user.getId(), user);
    }

    public User getUser(String userId) {
        return (User) redisTemplate.opsForHash().get(USER_KEY, userId);
    }

    public List<Object> getAllUsers() {
        return redisTemplate.opsForHash().values(USER_KEY);
    }

    public void deleteUser(String userId) {
        redisTemplate.opsForHash().delete(USER_KEY, userId);
    }
}

4.6. Tạo Controller UserController

// UserController.java
package com.example.myapp.controller;

import com.example.myapp.entity.User;
import com.example.myapp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping
    public ResponseEntity<Void> saveUser(@RequestBody User user) {
        userService.saveUser(user);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/{id}")
    public ResponseEntity<User> getUser(@PathVariable String id) {
        User user = userService.getUser(id);
        if (user != null) {
            return ResponseEntity.ok(user);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    @GetMapping
    public List<Object> getAllUsers() {
        return userService.getAllUsers();
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteUser(@PathVariable String id) {
        userService.deleteUser(id);
        return ResponseEntity.ok().build();
    }
}

4.7. Chạy ứng dụng

Chạy ứng dụng bằng cách sử dụng Maven:

mvn spring-boot:run

5. Kết luận

Trong bài viết này, chúng ta đã tìm hiểu về cách tích hợp Redis vào dự án Spring Boot, từ cấu hình kết nối đến sử dụng RedisTemplate để lưu trữ và truy xuất dữ liệu. Redis giúp cải thiện hiệu suất và khả năng mở rộng của ứng dụng bằng cách cung cấp một giải pháp lưu trữ dữ liệu trong bộ nhớ.

Trong bài viết tiếp theo, chúng ta sẽ tìm hiểu về cách cấu hình logging trong Spring Boot và sử dụng các framework logging như Logback và Log4j2 để ghi lại nhật ký ứng dụng một cách hiệu quả.

More from this blog

devngu

169 posts