首页 > 其他分享 >SpringCloud Alibaba入门2-common模块和user模块的基本开发

SpringCloud Alibaba入门2-common模块和user模块的基本开发

时间:2023-06-23 23:31:49浏览次数:35  
标签:23 SpringCloud mymall private Alibaba 模块 org import example

我们使用上一章节的项目环境进行开发。

https://blog.51cto.com/u_13312531/6536187

一、父项目引入SpringBoot

我们在父项目pom文件中统一管理引入的jar包的版本。我们采用父项目中以depencyMangement方式引入spring-boot,子项目依赖parent父配置即可。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>mymall</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!--设置为pom,管理依赖-->
    <packaging>pom</packaging>
    <modules>
        <module>mymall-common</module>
        <module>mymall-goods</module>
        <module>mymall-order</module>
        <module>mymall-pay</module>
        <module>mymall-stock</module>
        <module>mymall-user</module>
    </modules>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <!--统一管理项目依赖版本-->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.2.6.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>


二、common模块的开发

pom文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.example</groupId>
        <artifactId>myshop</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>myshop-common</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--hibernate-validate-->
        <dependency>
            <groupId>org.hibernate.validator</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.31</version>
        </dependency>
        <!--JPA-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
    </dependencies>
</project>

在父项目目录下创建application.yml配置文件,管理整个项目统一的配置。

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/mymall?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8&useSSL=false&rewriteBatchedStatements=true
    username: root
    password: 123456
 
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true

修改后的项目结构如下:

SpringCloud Alibaba入门2-common模块和user模块的基本开发_maven

我们在common模块中创建一个统一结果返回实体类CommonResult。

示例代码如下:

package com.example.mymall.common;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * @author qx
 * @date 2023/06/23
 * @desc 统一结果返回实体
 */
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class CommonResult implements Serializable {

    private Integer code;
    private String message;
    private Object data;

    public static CommonResult success() {
        return CommonResult.builder().code(200).message("请求成功").build();
    }

    public static CommonResult success(Object data) {
        return CommonResult.builder().code(200).message("请求成功").data(data).build();
    }

    public static CommonResult fail(String message) {
        return CommonResult.builder().code(500).message(message).build();
    }
}

使用JPA创建一个用户实体类

package com.example.mymall.entity;

import lombok.Data;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.UpdateTimestamp;

import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import java.util.Date;

/**
 * @author qx
 * @date 2023/06/23
 * @desc
 */
@Entity
@Table(name = "t_user")
@Data
@DynamicUpdate
@DynamicInsert
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    /**
     * 用户名
     */
    @NotBlank(message = "用户名不能为空")
    private String userName;

    /**
     * 用户性别:0:女 1:男  2:未知
     */
    private Integer sex;

    /**
     * 手机号
     */
    @NotBlank(message = "手机号不能为空")
    private String phone;

    /**
     * 邮箱
     */
    private String email;

    /**
     * 地址
     */
    private String address;

    /**
     * 积分
     */
    @Column(columnDefinition = "int default 0 comment '积分'")
    private Integer integral;

    /**
     * 等级
     */
    @Column(columnDefinition = "int default 1 comment '等级'")
    private Integer level;

    /**
     * 创建时间
     */
    @CreationTimestamp
    private Date createTime;

    /**
     * 修改时间
     */
    @UpdateTimestamp
    private Date updateTime;

    /**
     * 状态 1:正常 2:禁用
     */
    @Column(columnDefinition = "int default 1 comment '状态'")
    private Integer status;

}

三、user模块的开发

1.pom文件中引入common模块的依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.example</groupId>
        <artifactId>mymall</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>mymall-user</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.example</groupId>
            <artifactId>mymall-common</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>
</project>

2.创建数据访问层

package com.example.mymall.repository;

import com.example.mymall.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {
}

3.创建用户服务层

package com.example.mymall.service;

import com.example.mymall.entity.User;
import com.example.mymall.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author qx
 * @date 2023/06/23
 * @desc 用户服务层
 */
@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public void saveUser(User user) {
        userRepository.save(user);
    }

    public User getUserById(Long id) {
        return userRepository.findById(id).orElse(null);
    }
}

4.创建用户控制层

package com.example.mymall.controller;

import com.example.mymall.common.CommonResult;
import com.example.mymall.entity.User;
import com.example.mymall.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @author qx
 * @date 2023/06/23
 * @desc 用户控制层
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 添加用户
     */
    @PostMapping("/add")
    public CommonResult addUser(@Validated @RequestBody User user) {
        userService.saveUser(user);
        return CommonResult.success();
    }

    /**
     * 根据id获取用户信息
     *
     * @param id 用户ID
     * @return 用户信息
     */
    @GetMapping("/{id}")
    public CommonResult getUserById(@PathVariable("id") Long id) {
        return CommonResult.success(userService.getUserById(id));
    }

}

5.创建用户模块启动类

package com.example.mymall;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author qx
 * @date 2023/06/23
 * @desc 用户模块启动类
 */
@SpringBootApplication
public class MyMallUserApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyMallUserApplication.class, args);
    }
}

运行启动类,由于我们使用JPA机制自动创建了数据表

2023-06-23 23:08:14.997  INFO 9028 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
Hibernate: create table t_user (id bigint not null auto_increment, address varchar(255), create_time datetime(6), email varchar(255), integral int default 0 comment '积分', level int default 1 comment '等级', phone varchar(255), sex integer, status int default 1 comment '状态', update_time datetime(6), user_name varchar(255), primary key (id)) engine=InnoDB
2023-06-23 23:08:17.727  INFO 9028 --- [           main] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2023-06-23 23:08:17.736  INFO 9028 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2023-06-23 23:08:18.104  WARN 9028 --- [           main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2023-06-23 23:08:18.240  INFO 9028 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2023-06-23 23:08:18.449  INFO 9028 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2023-06-23 23:08:18.451  INFO 9028 --- [           main] c.example.mymall.MyMallUserApplication   : Started MyMallUserApplication in 6.21 seconds (JVM running for 7.61)

SpringCloud Alibaba入门2-common模块和user模块的基本开发_spring_02

6.测试

我们使用Postman进行接口的测试,首先测试用户新增接口

SpringCloud Alibaba入门2-common模块和user模块的基本开发_xml_03

我们刷新数据表,发现数据成功添加到了数据表中。

SpringCloud Alibaba入门2-common模块和user模块的基本开发_spring_04

继续测试用户查询接口

SpringCloud Alibaba入门2-common模块和user模块的基本开发_xml_05

到这里我们基本完成了公共模块和用户子模块的基本开发,其他功能可以自己去实现。

标签:23,SpringCloud,mymall,private,Alibaba,模块,org,import,example
From: https://blog.51cto.com/u_13312531/6539601

相关文章

  • 【雕爷学编程】Arduino动手做(121)---夏普粉尘传感器模块
    37款传感器与执行器的提法,在网络上广泛流传,其实Arduino能够兼容的传感器模块肯定是不止这37种的。鉴于本人手头积累了一些传感器和执行器模块,依照实践出真知(一定要动手做)的理念,以学习和交流为目的,这里准备逐一动手尝试系列实验,不管成功(程序走通)与否,都会记录下来—小小的进步或是搞......
  • ES6 模块化组件暴露方式
    分别<script>//分别exportconstschool=Vue.extend({data:{},methods:{}})</script> 统一<script>constschool=Vue.extend({data:{},......
  • ALU模块设计
    该文章主要记录ALU-DMA系统设计中ALU的设计点。1.ALU_TOP架构主要包含四个模块ALU_RF:主要由一个深度为16,宽度为32bits的双端口RAM组成。主要用于存放ALU中操作数。ALU_EXEC:主要根据输入的inst进行运算,执行乘法、加法,减法,与,或,异或,异或非等运算。ALU_FIFO:主要用于缓存ALU......
  • 【2】springCloud 2021 中间件基本使用方法
    RabbitMQBroker异步调用好处:吞吐量提升:无需等待订阅者处理完成,响应更快速故障隔离:服务没有直接调用,不存在级联失败问题调用间没有阻塞,不会造成无效的资源占用耦合度极低,每个服务都可以灵活插拔,可替换流量削峰:不管发布事件的流量波动多大,都由Broker接收,订阅者可以按照自......
  • 模块化和组件化的含义及区别
    1、模块化【代码逻辑角度划分】用于保证每个模块的只能单一比如药品管理,就是一个模块,包含了列表,添加,修改,删除;2、组件化【UI界面角度划分】页面上的每个独立区域,都可作为一个组件,便于组件复用3、区别划分角度不同4、为什么要使用模块化和组件化开发和调试的效率更高......
  • SpringCloud Alibaba入门1-创建多模块工程
    一、创建父项目创建一个Maven的父项目,命名为mymall用于管理子项目。项目创建完成后,删除src目录和在pom.xml文件里面设置packing的方式为pom,管理其他子模块的依赖。删除之后的项目结构为:二、创建子module在父项目上右键,新建module,命令为mymall-common,然后创建子模块创建子模块成......
  • SpringCloud依赖问题:spring-cloud-starter-eureka-server 和 spring-cloud-starter-ne
    学习SpringCloud微服务时,很多资料上都写的是spring-cloud-starter-eureka-server,结果问题无法正常启动,这是因为与当前的SpringBoot版本不匹配。其实较新的版本应该使用spring-cloud-starter-netflix-eureka-server依赖。PS:SpringCloud的版本不兼容好坑。......
  • nginx 的模块及处理流程
        nginx的内部结构是由核心部分和一系列的功能模块所组成。这样划分是为了使得每个模块的功能相对简单,便于开发,同时也便于对系统进行功能扩展。这样的模块化设计类似于面向对象中的接口类,它增强了nginx源码的可读性、可扩充性和可维护性。nginx的4种角色模块Nginx模块主要有......
  • 【雕爷学编程】Arduino动手做(119)---JQ6500语音模块
    37款传感器与执行器的提法,在网络上广泛流传,其实Arduino能够兼容的传感器模块肯定是不止这37种的。鉴于本人手头积累了一些传感器和执行器模块,依照实践出真知(一定要动手做)的理念,以学习和交流为目的,这里准备逐一动手尝试系列实验,不管成功(程序走通)与否,都会记录下来—小小的进步或是搞......
  • 【雕爷学编程】Arduino动手做(118)---PS2接口模块
    37款传感器与执行器的提法,在网络上广泛流传,其实Arduino能够兼容的传感器模块肯定是不止这37种的。鉴于本人手头积累了一些传感器和执行器模块,依照实践出真知(一定要动手做)的理念,以学习和交流为目的,这里准备逐一动手尝试系列实验,不管成功(程序走通)与否,都会记录下来—小小的进步或是搞......