在當今互聯網應用開發中,點贊功能幾乎成為了各類內容平臺的標配。它不僅能增加用戶與內容之間的互動,還能直觀地反映內容的受歡迎程度。本文將詳細介紹如何使用 Spring Boot 整合 Redis 來實現一個簡單的文章點贊功能,讓你輕松掌握這一實用技術。
一、Redis 簡介
Redis 是一個開源的、基于內存的數據結構存儲系統,它可以用作數據庫、緩存和消息中間件。Redis 支持多種數據結構,如字符串(String)、哈希(Hash)、列表(List)、集合(Set)和有序集合(Sorted Set)等,這使得它在處理各種場景時都能表現出色。其高性能、低延遲的特性,使其成為處理點贊、緩存等高頻讀寫場景的首選技術。
二、實驗目的與任務
本次實驗的核心目的是學習如何在 Spring Boot 項目中整合 Redis,實現一個簡單而實用的文章點贊功能。具體任務為:當用戶對一篇文章進行點贊操作時,點贊數在 Redis 緩存中實時加 1;當用戶取消點贊時,點贊數減 1。所有數據都存儲在 Redis 緩存中,以確保高效的讀寫操作。
三、實驗內容與要求
(一)環境準備
- Redis 安裝:
- 可以選擇 Windows 版或 Linux 版的 Redis 進行安裝。對于有虛擬機或云服務器的同學,建議嘗試 Linux 版安裝,以更好地模擬生產環境。
Windows 版安裝步驟:
D:
cd Redis
cd Redis-x64-3.2.100\
redis-server --service-install redis.windows.conf
?
- 從下載地址下載 Redis-x64-3.2.100.msi 安裝包。
- 將安裝包解壓到 D 盤的 Redis 文件夾中。
- 打開 cmd 指令窗口,依次輸入以下命令啟動 Redis 服務:
- 若要部署 Redis 在 Windows 下的服務,可輸入:
D:
cd Redis
cd Redis-x64-3.2.100\
redis-server --service-install redis.windows.conf
?
- RedisDesktopManager 安裝:
- RedisDesktopManager 是一個可視化操作 Redis 數據的工具,方便我們管理和查看 Redis 中的數據。
- 訪問相關鏈接下載并完成安裝,安裝完成后即可使用它連接到 Redis 服務。
(二)Spring Boot 項目配置
- 引入依賴:在項目的 pom.xml 文件中引入 Spring Boot 整合 Redis 的相關依賴:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
同時,為了構建完整的 Web 應用,還需引入 Spring Boot Web 和 Thymeleaf 等依賴:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
配置 Redis 屬性:在 src/main/resources/application.properties 文件中配置 Redis 相關屬性:
spring.redis.host=localhost
spring.redis.port=6379
這里假設 Redis 服務運行在本地,端口為默認的 6379。
(三)實現點贊功能
- 選擇 Redis 數據類型:
- 對于文章點贊信息,我們選用 Set 數據結構。Set 具有唯一性,非常適合存儲點贊用戶的標識,能確保每個用戶對同一篇文章只能點贊一次。鍵名格式為:article:{articleId}:likes。
- 為了統計點贊數量,我們使用 String 數據結構,鍵名格式為:article:like_count:{id}。
- 后端代碼實現:Redis 配置類:在 src/main/java/org/example/demo/config/RedisConfig.java 中配置 Redis 連接工廠和 RedisTemplate:
package org.example.demo.config;
import org.springframework.beans.factory.annotation.Value;
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.lettuce.LettuceConnectionFactory;
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 {@Value("${spring.redis.host}")private String host;@Value("${spring.redis.port}")private int port;@Beanpublic RedisConnectionFactory redisConnectionFactory() {return new LettuceConnectionFactory(host, port);}@Beanpublic RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {RedisTemplate<String, Object> template = new RedisTemplate<>();template.setConnectionFactory(factory);template.setKeySerializer(new StringRedisSerializer());template.setValueSerializer(new GenericJackson2JsonRedisSerializer());template.setHashKeySerializer(new StringRedisSerializer());template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());return template;}
}
- 文章服務類:在 src/main/java/org/example/demo/service/ArticleService.java 中實現點贊和獲取點贊數的業務邏輯:
package org.example.demo.service;import org.example.demo.model.Article;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;import java.util.concurrent.TimeUnit;@Service
public class ArticleService {private static final Logger logger = LoggerFactory.getLogger(ArticleService.class);@Autowiredprivate RedisTemplate<String, Object> redisTemplate;// 點贊/取消點贊public int likeArticle(int id) {try {String key = "article:likes:" + id;if (redisTemplate.opsForSet().isMember(key, "liked")) {// 已點贊,取消點贊redisTemplate.opsForSet().remove(key, "liked");String countKey = "article:like_count:" + id;// 處理點贊數遞減可能出現的空指針問題if (redisTemplate.hasKey(countKey)) {redisTemplate.opsForValue().decrement(countKey);}return 0;} else {// 未點贊,進行點贊redisTemplate.opsForSet().add(key, "liked");redisTemplate.opsForValue().increment("article:like_count:" + id);return 1;}} catch (Exception e) {logger.error("Error occurred while liking or unliking article with id: {}", id, e);return -1; // 返回 -1 表示操作異常}}public long getArticleLikeCount(int id) {try {String key = "article:like_count:" + id;Object value = redisTemplate.opsForValue().get(key);if (value == null) {return 0;}if (value instanceof Long) {return (Long) value;} else if (value instanceof Integer) {return ((Integer) value).longValue();} else {logger.error("Unexpected data type for like count of article with id: {}. Value: {}", id, value);return 0;}} catch (Exception e) {logger.error("Error occurred while getting like count for article with id: {}", id, e);return 0;}}
}
- 控制器類:在 src/main/java/org/example/demo/controller/MyController.java 中定義處理點贊請求的接口:
package org.example.demo.controller;import org.example.demo.model.Article;
import org.example.demo.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;@Controller
public class MyController {@Autowiredprivate ArticleService articleService;@GetMapping("/article/{id}")public String getArticleById(@PathVariable int id, Model model) {// 根據文章ID查詢文章內容Article article = articleService.getArticleById(id);// 將文章內容傳遞給前端頁面model.addAttribute("article", article);return "article";}@GetMapping("/article/{id}/like")@ResponseBodypublic int judgment(@PathVariable int id) {return articleService.likeArticle(id);}@GetMapping("/article/{id}/likeCount")@ResponseBodypublic long getArticleLikeCount(@PathVariable int id) {return articleService.getArticleLikeCount(id);}
}
- 前端代碼實現:在 src/main/resources/templates/article.html 中實現點贊按鈕的交互邏輯:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>文章詳情</title><!-- 引入Bootstrap CSS --><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet"><!-- 引入Font Awesome圖標庫 --><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css"><style>.like-btn {margin-top: 10px;}/* 定義選中文章的樣式 */.active-article {color: #0dcaf0; /* 這里可以根據喜好設置顏色,比如淺藍色 */}</style>
</head><body>
<div class="container-fluid"><nav class="navbar navbar-expand-lg navbar-dark bg-dark"><div class="container-fluid"><a class="navbar-brand" href="#">文章列表</a><button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"><span class="navbar-toggler-icon"></span></button><div class="collapse navbar-collapse" id="navbarNav"><ul class="navbar-nav"><li class="nav-item"><a class="nav-link" href="/article/1" onclick="highlightArticle(this)">文章一</a></li><li class="nav-item"><a class="nav-link" href="/article/2" onclick="highlightArticle(this)">文章二</a></li><li class="nav-item"><a class="nav-link" href="/article/3" onclick="highlightArticle(this)">文章三</a></li></ul></div></div></nav><div class="row"><div class="col-md-8 offset-md-2"><div class="card mt-4"><div class="card-body"><h1 class="card-title" th:text="${article.title}">Article Title</h1><p class="card-text text-muted">作者:<span th:text="${article.author}">Author</span>,出生時間:<span th:text="${article.date}">Date</span></p><p class="card-text" th:text="${article.content}">Article Content</p><button class="btn btn-primary like-btn" onclick="toggleLike()"><i class="fa-solid fa-thumbs-up"></i><span id="likeStatus0">點贊</span><span id="likeStatus1" style="display: none;">已點贊</span></button><span id="likeCount" class="ml-2"></span></div></div></div></div>
</div>
<!-- 引入Bootstrap JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>// 頁面加載時獲取點贊數量window.onload = function () {var articleId = window.location.pathname.split('/')[2];var xhr = new XMLHttpRequest();xhr.open('GET', '/article/' + articleId + '/likeCount', true);xhr.onreadystatechange = function () {if (xhr.readyState === XMLHttpRequest.DONE) {if (xhr.status === 200) {document.getElementById('likeCount').innerText = '點贊數:' + xhr.responseText;}}};xhr.send();}// 點贊按鈕點擊事件function toggleLike() {var articleId = window.location.pathname.split('/')[2];// 發送GET請求到后端var xhr = new XMLHttpRequest();xhr.open('GET', '/article/' + articleId + '/like', true);xhr.onreadystatechange = function () {if (xhr.readyState === XMLHttpRequest.DONE) {if (xhr.status === 200) {// 獲取后端返回的點贊狀態var likeStatus = parseInt(xhr.responseText);var likeStatus0 = document.getElementById('likeStatus0');var likeStatus1 = document.getElementById('likeStatus1');var likeBtn = document.querySelector('.like-btn');if (likeStatus === 1) {// 點贊成功console.log('點贊成功1');likeBtn.classList.remove('btn-primary');likeBtn.classList.add('btn-success');likeStatus0.style.display = 'none';likeStatus1.style.display = 'inline';} else {// 取消點贊console.log('取消點贊0');likeBtn.classList.remove('btn-success');likeBtn.classList.add('btn-primary');likeStatus0.style.display = 'inline';likeStatus1.style.display = 'none';}// 更新點贊數量var xhrCount = new XMLHttpRequest();xhrCount.open('GET', '/article/' + articleId + '/likeCount', true);xhrCount.onreadystatechange = function () {if (xhrCount.readyState === XMLHttpRequest.DONE) {if (xhrCount.status === 200) {document.getElementById('likeCount').innerText = '點贊數:' + xhrCount.responseText;}}};xhrCount.send();} else {console.error('請求失敗:' + xhr.status);}}};xhr.send();}// 點擊文章鏈接時高亮顯示當前文章function highlightArticle(link) {var navLinks = document.querySelectorAll('.navbar-nav a');navLinks.forEach(function (a) {a.classList.remove('active-article');});link.classList.add('active-article');}
</script>
</body></html>
四、步驟總結
- 完成 Redis 和 RedisDesktopManager 的安裝,并確保 Redis 服務正常運行。
- 在 Spring Boot 項目中引入相關依賴,配置 Redis 屬性。
- 編寫后端代碼,包括 Redis 配置類、文章服務類和控制器類,實現點贊和獲取點贊數的業務邏輯。
- 編寫前端代碼,實現點贊按鈕的交互邏輯,包括點贊狀態切換和點贊數更新。
- 使用 Maven 命令 mvn clean install 下載項目所需的依賴項,并編譯項目代碼,然后通過 mvn spring-boot:run 啟動項目。
- 使用 Postman 或瀏覽器訪問相關 URL,驗證項目功能是否正常。訪問http://localhost:8080/article/{articleId}/like進行文章點贊操作等。
五、運行截圖展示
運行 redis 截圖:展示 Redis 服務啟動后的界面,確保 Redis 正常運行。
運行文章界面:展示文章詳情頁面,包括文章標題、作者、內容等信息。
點贊文章界面:當用戶點擊點贊按鈕后,展示點贊成功后的界面,點贊按鈕樣式改變,點贊數實時更新。
取消文章點贊界面:當用戶再次點擊已點贊的按鈕取消點贊時,展示取消點贊后的界面,按鈕樣式恢復,點贊數相應減少。
通過以上步驟,我們成功實現了 Spring Boot 整合 Redis 的點贊功能。這一技術組合在實際項目中具有廣泛的應用場景,希望本文能幫助你快速掌握并應用到實際開發中。如果在實踐過程中有任何問題,歡迎在評論區留言交流。