Skip to main content

Command Palette

Search for a command to run...

Bài 18: Cấu hình Redis trong Spring Boot

Published
4 min readView as Markdown

Configurations chi tiết cho Redis trong Spring Boot:

Bước 1: Thêm dependency Redis trong dự án

  • Maven:

    • Mở file pom.xml và thêm dependency sau vào phần <dependencies>:

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

    • Mở file build.gradle và thêm dependency sau vào phần dependencies:

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

Bước 2: Cấu hình kết nối Redis trong application.properties hoặc application.yml

  • application.properties:

      spring.redis.host=localhost
      spring.redis.port=6379
      spring.redis.password=yourpassword (nếu cần)
      spring.redis.timeout=60000
      spring.redis.jedis.pool.max-idle=10
      spring.redis.jedis.pool.min-idle=1
      spring.redis.jedis.pool.max-active=10
      spring.redis.jedis.pool.max-wait=1000
    
  • application.yml:

      spring:
        redis:
          host: localhost
          port: 6379
          password: yourpassword (nếu cần)
          timeout: 60000
          jedis:
            pool:
              max-idle: 10
              min-idle: 1
              max-active: 10
              max-wait: 1000
    

Bước 3: Tạo Redis Configuration Class

  • Tạo một class cấu hình Redis để thiết lập RedisTemplateJedisConnectionFactory:

      import org.springframework.context.annotation.Bean;
      import org.springframework.context.annotation.Configuration;
      import org.springframework.data.redis.connection.RedisConnectionFactory;
      import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
      import org.springframework.data.redis.core.RedisTemplate;
      import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
      import org.springframework.data.redis.serializer.StringRedisSerializer;
      import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
    
      @Configuration
      public class RedisConfig {
    
          @Bean
          public RedisConnectionFactory redisConnectionFactory() {
              RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
              redisStandaloneConfiguration.setHostName("localhost");
              redisStandaloneConfiguration.setPort(6379);
              // Nếu Redis yêu cầu mật khẩu, bỏ chú thích dòng dưới và thay "yourpassword" bằng mật khẩu thực tế
              // redisStandaloneConfiguration.setPassword("yourpassword");
              return new JedisConnectionFactory(redisStandaloneConfiguration);
          }
    
          @Bean
          public RedisTemplate<String, Object> redisTemplate() {
              RedisTemplate<String, Object> template = new RedisTemplate<>();
              template.setConnectionFactory(redisConnectionFactory());
              template.setKeySerializer(new StringRedisSerializer());
              template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
              template.setHashKeySerializer(new StringRedisSerializer());
              template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
              return template;
          }
      }
    

Bước 4: Tạo Redis Service

  • Tạo một class RedisService để thao tác với Redis:

      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.data.redis.core.RedisTemplate;
      import org.springframework.stereotype.Service;
    
      @Service
      public class RedisService {
    
          @Autowired
          private RedisTemplate<String, Object> redisTemplate;
    
          public void saveData(String key, Object value) {
              redisTemplate.opsForValue().set(key, value);
          }
    
          public Object getData(String key) {
              return redisTemplate.opsForValue().get(key);
          }
    
          public void deleteData(String key) {
              redisTemplate.delete(key);
          }
      }
    

Bước 5: Tạo Redis Controller

  • Tạo một controller RedisController để kiểm tra việc lưu trữ và truy xuất dữ liệu từ Redis:

      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.web.bind.annotation.DeleteMapping;
      import org.springframework.web.bind.annotation.GetMapping;
      import org.springframework.web.bind.annotation.PostMapping;
      import org.springframework.web.bind.annotation.RequestMapping;
      import org.springframework.web.bind.annotation.RequestParam;
      import org.springframework.web.bind.annotation.RestController;
    
      @RestController
      @RequestMapping("/redis")
      public class RedisController {
    
          @Autowired
          private RedisService redisService;
    
          @PostMapping("/set")
          public String setData(@RequestParam String key, @RequestParam String value) {
              redisService.saveData(key, value);
              return "Data saved!";
          }
    
          @GetMapping("/get")
          public String getData(@RequestParam String key) {
              return "Data: " + redisService.getData(key);
          }
    
          @DeleteMapping("/delete")
          public String deleteData(@RequestParam String key) {
              redisService.deleteData(key);
              return "Data deleted!";
          }
      }
    

Bước 6: Kiểm tra ứng dụng

Ví dụ thực tiễn:

Lưu trữ thông tin người dùng

  • Tạo một class User để đại diện cho thông tin người dùng:

      import java.io.Serializable;
    
      public class User implements Serializable {
          private String id;
          private String name;
          private String email;
    
          // Constructors, getters and setters
          public User() {}
    
          public User(String id, String name, String email) {
              this.id = id;
              this.name = name;
              this.email = email;
          }
    
          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 String getEmail() {
              return email;
          }
    
          public void setEmail(String email) {
              this.email = email;
          }
      }
    
  • Cập nhật RedisService để hỗ trợ lưu trữ thông tin người dùng:

      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.data.redis.core.RedisTemplate;
      import org.springframework.stereotype.Service;
    
      @Service
      public class RedisService {
    
          @Autowired
          private RedisTemplate<String, Object> redisTemplate;
    
          public void saveUser(String key, User user) {
              redisTemplate.opsForValue().set(key, user);
          }
    
          public User getUser(String key) {
              return (User) redisTemplate.opsForValue().get(key);
          }
    
          public void deleteUser(String key) {
              redisTemplate.delete(key);
          }
      }
    
  • Cập nhật RedisController để hỗ trợ các thao tác với thông tin người dùng:

      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.web.bind.annotation.*;
    
      @RestController
      @RequestMapping("/user")
      public class UserController {
    
          @Autowired
          private RedisService redisService;
    
          @PostMapping("/set")
          public String setUser(@RequestParam String key, @RequestParam String name, @RequestParam String email) {
              User user = new User(key, name, email);
              redisService.saveUser(key, user);
              return "User saved!";
          }
    
          @GetMapping("/get")
          public User getUser(@RequestParam String key) {
              return redisService.getUser(key);
          }
    
          @DeleteMapping("/delete")
          public String deleteUser(@RequestParam String key) {
              redisService.deleteUser(key);
              return "User deleted!";
          }
      }
    
  • Kiểm tra ứng dụng với thông tin người dùng:

Kết luận:

  • Bằng cách sử dụng Spring Boot và Redis, bạn có thể dễ dàng cấu hình và quản lý kết nối Redis, cũng như thực hiện các thao tác lưu trữ, truy xuất và xóa dữ liệu. Bài viết này đã cung cấp các bước chi tiết để cấu hình Redis trong Spring Boot, từ việc thêm dependency, cấu hình kết nối, đến việc tạo các lớp service và controller để thao tác với dữ liệu. Qua đó, bạn có thể áp dụng vào các dự án thực tế để cải thiện hiệu suất và khả năng mở rộng của ứng dụng, đặc biệt là trong các hệ thống yêu cầu xử lý dữ liệu nhanh chóng và thời gian thực.

More from this blog

devngu

169 posts