Skip to main content

Command Palette

Search for a command to run...

Bài 16: Cài đặt Spring Boot và Redis

Published
4 min readView as Markdown

Hướng dẫn tạo dự án Spring Boot:

Bước 1: Tạo dự án bằng Spring Initializr

  • Truy cập Spring Initializr:

  • Cấu hình dự án:

    • Project: Chọn Maven Project hoặc Gradle Project tùy thuộc vào hệ thống build bạn sử dụng.

    • Language: Chọn Java.

    • Spring Boot Version: Chọn phiên bản Spring Boot mới nhất (ví dụ: 2.5.4).

    • Project Metadata:

      • Group: Nhập group ID cho dự án, ví dụ: com.example.

      • Artifact: Nhập artifact ID cho dự án, ví dụ: redis-demo.

      • Name: Tên dự án, ví dụ: redis-demo.

      • Description: Mô tả dự án, ví dụ: Demo project for Spring Boot with Redis.

      • Package Name: Tên package, ví dụ: com.example.redis-demo.

      • Packaging: Chọn Jar.

      • Java Version: Chọn phiên bản Java bạn sử dụng (ví dụ: 11).

  • Thêm Dependencies:

    • Nhấp vào nút Add Dependencies và thêm các dependencies sau:

      • Spring Web

      • Spring Data Redis

      • Lombok (tùy chọn, nếu bạn muốn sử dụng Lombok để giảm boilerplate code)

      • Spring Boot DevTools (tùy chọn, nếu bạn muốn sử dụng công cụ phát triển của Spring Boot)

  • Tạo dự án:

    • Nhấp vào nút Generate để tải xuống file nén của dự án.

    • Giải nén file này vào thư mục làm việc của bạn.

Bước 2: Import dự án vào IDE

  • IntelliJ IDEA:

    • Mở IntelliJ IDEA, chọn File > New > Project from Existing Sources.

    • Chọn thư mục dự án đã giải nén, nhấp OK.

    • Chọn Import project from external model, chọn Maven hoặc Gradle tùy thuộc vào hệ thống build bạn chọn.

    • Nhấp Finish để hoàn tất quá trình import.

  • Eclipse:

    • Mở Eclipse, chọn File > Import.

    • Chọn Existing Maven Projects và nhấp Next.

    • Chọn thư mục dự án đã giải nén, nhấp Finish.

Tích hợp Redis vào dự án:

Bước 1: Thêm dependency Redis trong Maven/Gradle

  • 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 Redis trong Spring Boot

  • 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)
      
    • application.yml:

        spring:
          redis:
            host: localhost
            port: 6379
            password: yourpassword (nếu cần)
      
  • Tạo Redis Configuration Class:

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

        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;
            }
        }
      

Bước 3: Kiểm tra kết nối và lưu trữ dữ liệu

  • Tạo một class kiểm tra kết nối và lưu trữ dữ liệu:

    • 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);
            }
        }
      
  • Tạo một controller để kiểm tra:

    • 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.GetMapping;
        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;
      
            @GetMapping("/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);
            }
        }
      
  • Kiểm tra ứng dụng:

Kết luận:

  • Qua bài viết này, bạn đã biết cách tạo một dự án Spring Boot, tích hợp Redis vào dự án, và cấu hình kết nối Redis. Bạn cũng đã thực hiện kiểm tra việc lưu trữ và truy xuất dữ liệu từ Redis thông qua Spring Boot. Đây là bước khởi đầu quan trọng để bạn có thể sử dụng Redis trong các dự án Spring Boot của mình. Việc sử dụng Redis giúp 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