Các hệ thống ngày nay luôn tìm cách tối ưu performance và Redis gần như là một mảnh ghép không thể thiếu trong đó. Hôm nay chúng ta sẽ cùng tìm hiểu cách kết nối ứng dụng Spring Boot với Redis.
Ưu và nhược điểm của Redis là gì?
Redis hiện đang được tin dùng bởi hơn 5000 công ty trên toàn thế giới, trong đó có cả nhiều ông lớn như Snapchat, Twitter, Slack, Uber, Airbnb và Pinterest. Vậy ưu và nhược điểm của Redis là gì? Có nên xem Redis là giải pháp duy nhất hay không?

Điểm mạnh của Redis
- Tốc độ cực nhanh.
- Dễ thiết lập và sử dụng.
- Hỗ trợ nhiều cấu trúc dữ liệu linh hoạt.
- Cho phép lưu trữ các cặp key-value với kích thước lên đến 512MB.
- Sử dụng cơ chế hash riêng (Redis Hashing).
- Không bị downtime và ảnh hưởng hiệu suất khi thay đổi quy mô.
- Mã nguồn mở, ổn định.
- Hỗ trợ nhiều ngôn ngữ khác nhau: Java, Python, PHP, C, C++, C#, JavaScript, Node.js, Ruby, R, Go,…
Điểm yếu
- Dữ liệu được chia sẻ dựa trên các vị trí hash gán cho từng Master. Vì vậy nếu Master đang giữ slot gặp trục trặc, dữ liệu trong slot đó cũng sẽ bị mất.
- Client kết nối đến các cluster Redis nên chú ý đến cấu trúc liên kết cụm.
- Khi sử dụng Redis cần nhiều RAM vì cơ chế in-memory.
Config redis và Spring boot
Cài đặt
Chúng ta sử dụng Maven, và yêu cầu các dependencies sau:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
</dependency>
<dependency>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
<version>5.1.3.RELEASE</version>
</dependency>
</dependencies>
Trong đó, spring-data-redis
là thư viện của Spring giúp chúng ta thao tác với Redis dễ dàng hơn.
Còn lettuce-core
là một thư viện mã nguồn mở, giúp kết nối tới Redis một cách thread-safe bằng nhiều hình thức như synchronous, asynchronous and reactive usage.
Trong bài này chúng ta sẽ cấu hình cho spring-data-redis
sử dụng lettuce
kết nối tới Redis. Còn chi tiết về letture
sẽ được đề cập ở một bài viết khác.
Implement
Cấu hình Redis
Bài viết giả định bạn đã cài đặt Redis, để kết nối tới Redis, bạn cần cung cấp địa chỉ host
và port
cho lettuce.
Cách dễ nhất là ghi nó ở file application.properties trong thư mục resources:
application.properties
redis:
host: "localhost"
port: "6379"
package com.renwei.uz.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
@Configuration
public class RedisConfig {
@Value("${redis.host}")
private String redisHost;
@Value("${redis.port}")
private int redisPort;
@Bean
public LettuceConnectionFactory redisConnectionFactory() {
return new LettuceConnectionFactory(new RedisStandaloneConfiguration(redisHost, redisPort));
}
@Bean
@Primary
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
Chúng ta cần sử dụng lettuce
để kết nối tới Redis, nên tôi tạo ra bean LettuceConnectionFactory
và Spring Data sẽ tự động nhận vào cấu hình của mình.
Trong ví dụ này, chúng ta làm việc với Redis Standalone RedisStandaloneConfiguration
. Còn nếu bạn muốn cấu hình với Redis Cluster thì cũng tương tự bằng class RedisClusterConfiguration
.
Ở đây tôi cấu hình cho RedisTemplate
nhận key là Object
và value cũng là Object
luôn. Để chúng ta có thể lưu bất kỳ key-value nào xuống Redis.
Chạy thử
Chúng ta tạo ra một class distancePlace2Place
implements CommandLineRunner
để chạy một ví dụ lưu lại thông tin tìm kiếm địa chỉ trên gg map tránh việc call api gg map nhiều làm phát sinh chi phí:

Lấy dữ liệu từ redis dựa trên key from-to

Put dữ liệu lên redis

Kết
Tới đây các bạn có thể dễ dàng thao tác với các kiểu cấu trúc trong Redis thông qua RedisTemplate
.
8 comments
When I originally commented I clicked the “Notify me when new comments are added” checkbox and now
each time a comment is added I get four e-mails with the same comment.
Is there any way you can remove me from that service?
Cheers!
You actually make it seem so easy with your presentation but I find this topic to be really something
which I think I would never understand. It seems too complex and
extremely broad for me. I am looking forward for your
next post, I will try to get the hang of it!
Hi there! This is my first comment here so I just wanted to give
a quick shout out and say I truly enjoy reading through your blog posts.
Can you suggest any other blogs/websites/forums that
deal with the same topics? Appreciate it!
Great post. I was checking constantly this blog and I’m impressed!
Very useful info particularly the last part
🙂 I care for such information much. I was seeking this particular information for a very long
time. Thank you and good luck.
Howdy! I know this is sort of off-topic however
I needed to ask. Does building a well-established website like yours take a large amount of work?
I am completely new to operating a blog however I do write in my journal
daily. I’d like to start a blog so I can easily share my
experience and views online. Please let me know if you
have any kind of suggestions or tips for brand new aspiring bloggers.
Appreciate it!
whoah this weblog is great i really like reading your posts.
Keep up the great work! You know, many individuals are looking around for this info, you could help them greatly.
Thanks for your marvelous posting! I seriously enjoyed
reading it, you are a great author. I will ensure
that I bookmark your blog and will often come back at
some point. I want to encourage one to continue your
great writing, have a nice afternoon!
Hi, its fastidious article on the topic of media print, we all
be aware of media is a impressive source of facts.