Spring Boot 實戰:構建一個社交平臺 API

? ? ? ?在這篇博客中,我們將繼續深入 Spring Boot 的開發實踐,通過構建一個簡單的社交平臺 API,幫助大家理解如何使用 Spring Boot 高效地開發一個具有注冊、登錄、個人資料管理、帖子發布與評論、點贊等功能的社交平臺。在開發過程中,我們將結合 Spring Security、Spring Data JPA、Spring Boot Actuator、Redis 緩存等技術,全面展示如何在實際項目中應用這些高級特性。


項目架構

? ? ? ?這個社交平臺將包括以下核心模塊:

  1. 用戶認證與管理(注冊、登錄、個人資料管理)
  2. 帖子管理(發布、查看、刪除、點贊)
  3. 評論功能(對帖子進行評論、查看評論)
  4. 緩存優化(使用 Redis 加速頻繁查詢)
  5. 消息通知(發布、刪除帖子時發送通知)

技術棧

  • 后端框架:Spring Boot、Spring Security、Spring Data JPA、Spring Web
  • 數據庫:MySQL(存儲用戶、帖子、評論等數據)
  • 緩存:Redis(加速用戶和帖子數據查詢)
  • 消息隊列:RabbitMQ(處理異步任務)
  • 前端:Vue.js 或 React(本篇僅關注后端)

1. 搭建基礎項目框架

1.1 創建 Spring Boot 項目

? ? ? ?首先,使用 Spring Initializr 創建一個新的 Spring Boot 項目,選擇以下依賴:

  • Spring Web:用于構建 RESTful API。
  • Spring Data JPA:用于數據庫持久化操作。
  • Spring Security:用于用戶認證和授權。
  • MySQL Driver:用于數據庫連接。
  • Spring Boot DevTools:加速開發過程。
  • Spring Boot Starter Cache:支持緩存功能。
  • Spring Boot Starter AMQP:用于集成消息隊列(RabbitMQ)。

1.2 項目結構

? ? ? ?我們將項目分為多個模塊,每個模塊負責不同的業務邏輯:

social-platform/
├── src/
│   ├── main/
│   │   ├── java/
│   │   │   └── com.example.socialplatform/
│   │   │       ├── controller/
│   │   │       ├── model/
│   │   │       ├── repository/
│   │   │       ├── service/
│   │   │       ├── security/
│   │   │       └── SocialPlatformApplication.java
│   │   └── resources/
│   │       ├── application.properties
│   │       └── application.yml
├── pom.xml
└── README.md

2. 用戶認證與管理

2.1 用戶實體和注冊功能

? ? ? ?首先,我們定義一個 User 實體類,用于存儲用戶信息。

@Entity
public class User {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;private String username;private String email;private String password;private String role;// Getters and Setters
}
2.1.1 用戶注冊 API

? ? ? ?我們創建一個 UserController 來處理用戶的注冊請求。

@RestController
@RequestMapping("/auth")
public class UserController {@Autowiredprivate UserService userService;@PostMapping("/register")public ResponseEntity<String> register(@RequestBody User user) {userService.register(user);return ResponseEntity.ok("Registration successful!");}
}
2.1.2 密碼加密與保存

? ? ? ?使用 Spring Security 提供的 BCryptPasswordEncoder 來加密用戶的密碼。

@Service
public class UserService {@Autowiredprivate UserRepository userRepository;@Autowiredprivate BCryptPasswordEncoder passwordEncoder;public void register(User user) {user.setPassword(passwordEncoder.encode(user.getPassword()));  // 密碼加密user.setRole("USER");  // 默認角色為用戶userRepository.save(user);}
}

2.2 用戶認證與權限管理

2.2.1 配置 Spring Security

? ? ? ?在 WebSecurityConfig 中配置用戶認證和權限管理。

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate CustomUserDetailsService userDetailsService;@Overrideprotected void configure(HttpSecurity http) throws Exception {http.csrf().disable().authorizeRequests().antMatchers("/auth/register", "/auth/login").permitAll().anyRequest().authenticated()  // 其他請求需要認證.and().formLogin().loginPage("/auth/login").permitAll().and().logout().permitAll();}@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());}
}
2.2.2 自定義 UserDetailsService

? ? ? ?通過自定義 UserDetailsService 來加載用戶的認證信息。

@Service
public class CustomUserDetailsService implements UserDetailsService {@Autowiredprivate UserRepository userRepository;@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {User user = userRepository.findByUsername(username).orElseThrow(() -> new UsernameNotFoundException("User not found"));return new UserPrincipal(user);}
}

3. 帖子管理功能

3.1 帖子實體與數據庫操作

? ? ? ?我們定義一個 Post 實體,用于存儲用戶發布的帖子。

@Entity
public class Post {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;private Long userId;private String content;private LocalDateTime createdAt;// Getters and Setters
}

3.2 帖子服務與控制器

3.2.1 創建與獲取帖子

? ? ? ?在 PostService 中,我們實現帖子創建和獲取的功能。

@Service
public class PostService {@Autowiredprivate PostRepository postRepository;public Post createPost(Post post) {post.setCreatedAt(LocalDateTime.now());return postRepository.save(post);}public List<Post> getAllPosts() {return postRepository.findAll();}
}
3.2.2 帖子控制器

? ? ? ?創建帖子控制器來處理用戶的請求。

@RestController
@RequestMapping("/posts")
public class PostController {@Autowiredprivate PostService postService;@PostMappingpublic ResponseEntity<Post> createPost(@RequestBody Post post) {Post createdPost = postService.createPost(post);return ResponseEntity.ok(createdPost);}@GetMappingpublic ResponseEntity<List<Post>> getAllPosts() {return ResponseEntity.ok(postService.getAllPosts());}
}

4. 評論與點贊功能

4.1 評論實體與數據庫操作

? ? ? ?我們定義一個 Comment 實體,用于存儲用戶對帖子的評論。

@Entity
public class Comment {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;private Long postId;private Long userId;private String content;private LocalDateTime createdAt;// Getters and Setters
}

4.2 點贊功能

? ? ? ?我們通過創建一個 Like 實體來記錄用戶對帖子或評論的點贊信息。

@Entity
public class Like {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;private Long postId;private Long userId;// Getters and Setters
}

5. 緩存優化

5.1 使用 Redis 緩存帖子

? ? ? ?在 PostService 中,我們使用 Redis 緩存來加速頻繁訪問的帖子數據。

5.1.1 配置 Redis

? ? ? ?在 application.yml 中配置 Redis:

spring:cache:type: redisredis:host: localhostport: 6379
5.1.2 緩存帖子

? ? ? ?使用 @Cacheable 注解將獲取帖子的方法緩存到 Redis 中。

@Service
public class PostService {@Autowiredprivate PostRepository postRepository;@Cacheable(value = "posts", key = "#id")public Post getPostById(Long id) {return postRepository.findById(id).orElseThrow(() -> new RuntimeException("Post not found"));}
}

6. 消息通知功能

? ? ? ?當用戶發布帖子或評論時,我們通過 RabbitMQ 發送通知消息。

6.1 配置 RabbitMQ

? ? ? ?在 application.yml 中配置 RabbitMQ:

spring:rabbitmq:host: localhostport: 5672username: guestpassword: guest

6.2 消息發送與接收

6.2.1 消息發送

? ? ? ?在 PostService 中,我們向 RabbitMQ 發送消息:

@Service
public class PostService {@Autowiredprivate RabbitTemplate rabbitTemplate;public Post createPost(Post post) {// 保存帖子postRepository.save(post);// 發送消息rabbitTemplate.convertAndSend("socialExchange", "post.created", post);return post;}
}
6.2.2 消息接收

? ? ? ?通過 @RabbitListener 注解接收并處理消息:

@Service
public class NotificationService {@RabbitListener(queues = "socialQueue")public void receiveMessage(Post post) {// 處理通知邏輯System.out.println("New Post Created: " + post.getContent());}
}

7. 總結

? ? ? ?通過本篇博客,我們構建了一個簡單的社交平臺 API,涵蓋了用戶注冊、登錄、帖子管理、評論與點贊、消息通知等功能,并結合 Redis 緩存、RabbitMQ 消息隊列等技術進行優化。通過這個項目,我們深入了解了 Spring Boot 的多種高級特性,如 Spring Security、Spring Data JPA、緩存和消息隊列的使用。

? ? ? ?隨著項目的不斷擴展,你可以進一步增強系統的安全性、性能和可擴展性,例如增加支付系統、推送通知、文件上傳等功能。希望這篇文章能幫助你在實際開發中更好地運用 Spring Boot 構建高效、可靠的應用。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/62967.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/62967.shtml
英文地址,請注明出處:http://en.pswp.cn/web/62967.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

配置mysqld(讀取選項內容,基本配置),數據目錄(配置的必要性,目錄下的內容,具體文件介紹,修改配置)

目錄 配置mysqld 讀取選項內容 介紹 啟動腳本 基本配置 內容 端口號 數據目錄的路徑 配置的必要性 配置路徑 mysql數據目錄 具體文件 修改配置時 權限問題 配置mysqld 讀取選項內容 介紹 會從[mysqld] / [server] 節點中讀取選項內容 優先讀取[server] 雖然服務…

智能家居WTR096-16S錄放音芯片方案,實現語音播報提示及錄音留言功能

前言&#xff1a; 在當今社會的高速運轉之下&#xff0c;夜幕低垂之時&#xff0c;許多辛勤工作的父母尚未歸家。對于肩負家庭責任的他們而言&#xff0c;確保孩童按時用餐與居家安全成為心頭大事。此時&#xff0c;家居留言錄音提示功能應運而生&#xff0c;恰似家中的一位無形…

Java 編程基礎:開啟編程世界的大門

一、Java 環境搭建 在開始編寫 Java 代碼之前&#xff0c;我們需要先搭建 Java 開發環境。 1. 安裝 JDK&#xff08;Java Development Kit&#xff09; JDK 是 Java 開發的核心工具包&#xff0c;它包含了編譯 Java 源文件所需的編譯器&#xff08;javac&#xff09;以及運行…

pytorch bilstm crf的教程,注意 這里不支持批處理,要支持批處理 用torchcrf這個。

### Bi-LSTM Conditional Random Field ### pytorch tutorials https://pytorch.org/tutorials/beginner/nlp/advanced_tutorial.html ### 模型主要結構&#xff1a; ![title](sources/bilstm.png) pytorch bilstm crf的教程&#xff0c;注意 這里不支持批處理 Python version…

【SickOs1.1靶場滲透】

文章目錄 一、基礎信息 二、信息收集 三、反彈shell 四、提權 一、基礎信息 Kali IP&#xff1a;192.168.20.146 靶機IP&#xff1a;192.168.20.150 二、信息收集 端口掃描 nmap -sS -sV -p- -A 192.168.20.150 開放了22、3128端口&#xff0c;8080端口顯示關閉 22端…

【HF設計模式】03-裝飾者模式

聲明&#xff1a;僅為個人學習總結&#xff0c;還請批判性查看&#xff0c;如有不同觀點&#xff0c;歡迎交流。 摘要 《Head First設計模式》第3章筆記&#xff1a;結合示例應用和代碼&#xff0c;介紹裝飾者模式&#xff0c;包括遇到的問題、遵循的 OO 原則、達到的效果。 …

Mysql數據庫中,什么情況下設置了索引但無法使用?

在MySQL數據庫中&#xff0c;即使已經正確設置了索引&#xff0c;但在某些情況下索引可能無法被使用。 以下是一些常見的情況&#xff1a; 1. 數據分布不均勻 當某個列的數據分布非常不均勻時&#xff0c;索引可能無法有效地過濾掉大部分的數據&#xff0c;導致索引失效。 …

秒殺業務中的庫存扣減為什么不加分布式鎖?

前言 說到秒殺業務的庫存扣減&#xff0c;就還是得先確認我們的扣減基本方案。 秒殺場景的庫存扣減方案 一般的做法是&#xff0c;先在Redis中做扣減&#xff0c;然后發送一個MQ消息&#xff0c;消費者在接到消息之后做數據庫中庫存的真正扣減及業務邏輯操作。 如何解決數據…

ChatGPT生成測試用例的最佳實踐(一)

前面介紹的案例主要展示了ChatGPT在功能、安全和性能測試用例生成方面的應用和成果。通過ChatGPT生成測試用例&#xff0c;測試團隊不僅可以提升工作效率&#xff0c;還可以加快測試工作的速度&#xff0c;盡早發現被測系統中的問題。問題及早發現有助于提高軟件的質量和用戶滿…

基于Redis實現令牌桶算法

基于Redis實現令牌桶算法 令牌桶算法算法流程圖優點缺點 實現其它限流算法 令牌桶算法 令牌桶是一種用于分組交換和電信網絡的算法。它可用于檢查數據包形式的數據傳輸是否符合定義的帶寬和突發性限制&#xff08;流量不均勻或變化的衡量標準&#xff09;。它還可以用作調度算…

操作系統(8)死鎖

一、概念 死鎖是指在一個進程集合中的每個進程都在等待只能由該集合中的其他進程才能引起的事件&#xff0c;而無限期地僵持下去的局面。在多任務環境中&#xff0c;由于資源分配不當&#xff0c;導致兩個或多個進程在等待對方釋放資源時陷入無限等待的狀態&#xff0c;這就是死…

Micropython 擴展C模塊<HelloWorld>

開發環境 MCU&#xff1a;Pico1&#xff08;無wifi版&#xff09;使用固件&#xff1a;自編譯版本開發環境&#xff1a;MacBook Pro Sonoma 14.5開發工具&#xff1a;Thonny 4.1.6開發語言&#xff1a;MicroPython 1.24 執行示例 在github上獲取micropython&#xff0c;我使…

并查集基礎

abstract 并查集&#xff08;Union-Find Set&#xff09;是一種數據結構&#xff0c;主要用于處理動態連通性問題&#xff08;Dynamic Connectivity Problem&#xff09;&#xff0c;例如在圖論中判斷兩點是否屬于同一個連通分量&#xff0c;以及動態地合并集合。 它廣泛應用…

CloudberryDB(一)安裝部署多節點分布式數據庫集群

CloudberryDB&#xff1a; 一個 Greenplum Database 分布式數據庫開源版本的衍生項目&#xff0c; 針對開源 Greenplum Database 優化的地方&#xff0c; CloudberryDB制定了路線圖&#xff08;https://github.com/orgs/cloudberrydb/discussions/369&#xff09;并在逐步改…

解決Logitech G hub 無法進入一直轉圈的方案(2024.12)

如果你不是最新版本無法加載嘗試以下方案&#xff1a;刪除AppData 文件夾下的logihub文件夾 具體路徑&#xff1a;用戶名根據實際你的請情況修改 C:\Users\Administrator\AppData\Local 如果你有通過lua編譯腳本&#xff0c;記得備份&#xff01;&#xff01; ↓如果你是最新…

數據庫范式與反范式化:如何權衡性能與數據一致性

目錄 1. 什么是數據庫范式&#xff08;Normalization&#xff09;&#xff1f;第一范式&#xff08;1NF&#xff09;第二范式&#xff08;2NF&#xff09;第三范式&#xff08;3NF&#xff09; 2. 什么是反范式化&#xff08;Denormalization&#xff09;&#xff1f;3. 反范式…

Nmap使用總結

0X00 背景 nmap是測試中常用的網絡探測工具&#xff0c;但是這回簡單的操作&#xff0c;一直了解不深入&#xff0c;現在深入的了解和學習一下。 在文章結構上&#xff0c;我把平時常用的內容提前了&#xff0c;以便再次查閱的時候&#xff0c;比較方便。 0X01 安裝 nmap可…

【記錄49】vue2 vue-office在線預覽 docx、pdf、excel文檔

vue2 在線預覽 docx、pdf、excel文檔 docx npm install vue-office/docx vue-demi0.14.6 指定版本 npm install vue-office/docx vue-demi <template><VueOfficeDocx :src"pdf" style"height: 100vh;" rendere"rendereHandler" error&…

MVC模式的理解和實踐

在軟件開發中&#xff0c;MVC&#xff08;Model-View-Controller&#xff09;模式是一種經典的設計模式&#xff0c;特別適用于構建用戶界面復雜的Web應用程序。MVC通過將應用程序的業務邏輯、數據顯示和用戶交互分離&#xff0c;使代碼結構更加清晰&#xff0c;易于維護和擴展…

[A-22]ARMv8/v9-SMMU多級頁表架構

ver0.1 [看前序文章有驚喜,關注W\X\G=Z+H=“浩瀚架構師”,可以解鎖全部文章] 前言 前文我們對SMMU的系統架構和基本功能做了簡要的介紹,現在大家大致對SMMU在基于ARM體系的系統架構下的總線位置和產品形態有了基本的了解。這里我們還是簡單做個前情回顧,從總線架構角度看…