新手入门系列-springboot项目初体验
新手入门系列-springboot项目初体验
在现代 Java 开发中,SpringBoot 已成为构建应用程序的首选框架。本文将详细介绍如何从零开始搭建一个 SpringBoot 项目,并实现 MySQL 数据库和 Redis 缓存的整合。我们将创建一个简单的用户管理系统,展示数据库操作和缓存使用的最佳实践。
一、环境准备
在开始前,请确保你的开发环境已安装以下组件:
- JDK 8 或更高版本
- Maven 3.6 或更高版本
- MySQL 5.7 或更高版本
- Redis 5.0 或更高版本
- IDE(推荐 IntelliJ IDEA 或 Spring Tool Suite)
二、创建 SpringBoot 项目
1. 使用 Spring Initializr 创建项目
访问 Spring Initializr 网站,按照以下内容配置:
- Project:Maven Project
- Language:Java
- Spring Boot:2.7.x(或最新稳定版)
- Group:com.example
- Artifact:springboot-redis-mysql-demo
- Name:springboot-redis-mysql-demo
- Package name:com.example.demo
- Packaging:Jar
- Java:8 或更高版本
2. 添加依赖
在依赖部分添加以下组件:
- Spring Web
- Spring Data JPA
- Spring Data Redis
- MySQL Driver
- Lombok
- Validation
生成并下载项目后,解压到你的工作目录。
三、配置数据库和缓存连接
1. 创建 MySQL 数据库
登录 MySQL,创建项目使用的数据库:
CREATE DATABASE springboot_demo DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
2. 配置 application.properties
打开 src/main/resources/application.properties
文件,添加以下配置:
# 应用名称和端口
spring.application.name=springboot-redis-mysql-demo
server.port=8080# MySQL 数据库配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot_demo?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=your_password# JPA 配置
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true# Redis 配置
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
spring.redis.database=0
spring.redis.timeout=10000
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-wait=-1
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.min-idle=0
需要将 your_password
替换为你的 MySQL 密码。
四、创建实体类
1. 用户实体类
创建 src/main/java/com/example/demo/entity/User.java
文件:
package com.example.demo.entity;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDateTime;@Data
@Entity
@Table(name = "users")
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {private static final long serialVersionUID = 1L;@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;@Column(nullable = false, length = 50, unique = true)private String username;@Column(nullable = false, length = 100)private String password;@Column(length = 50)private String email;@Column(name = "created_at")private LocalDateTime createdAt;@Column(name = "updated_at")private LocalDateTime updatedAt;@PrePersistprotected void onCreate() {createdAt = LocalDateTime.now();updatedAt = LocalDateTime.now();}@PreUpdateprotected void onUpdate() {updatedAt = LocalDateTime.now();}
}
五、创建数据访问层
1. 用户仓库接口
创建 src/main/java/com/example/demo/repository/UserRepository.java
文件:
package com.example.demo.repository;import com.example.demo.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;import java.util.Optional;@Repository
public interface UserRepository extends JpaRepository<User, Long> {Optional<User> findByUsername(String username);boolean existsByUsername(String username);boolean existsByEmail(String email);
}
六、配置 Redis 缓存
1. Redis 配置类
创建 src/main/java/com/example/demo/config/RedisConfig.java
文件:
package com.example.demo.config;import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager