遇一山,过一山,处处有风景;只要勇敢向前,一路尽是繁花盛开。 | (点击查看→)【测试干货】python/java自动化、持续集成、性能、测开、简历、笔试面试等

SpringBoot开发Restful API及使用jmeter测试

 

Restful API简介

Representational State Transfer,简称为REST, 即表现层状态转化,简单来说,客户端通过HTTP方法对服务器的资源进行操作, 实现表现层状态转化

GET:获取资源

POST:新建资源

PUT:更新资源

DELETE:删除资源

Restful 是目前最流行的 API 设计规范,用于 Web 数据接口的设计;

构建Restful API的目的通常都是由于多终端的原因,这些终端会共用很多底层业务逻辑,因此我们会抽象出这样一层来同时服务于多个移动端或者Web前端。

 

Restful API设计原则

1、API的版本应该在URL中体现,如 http://api.qzcsbj.com/v2

2、URL中不要使用动词,应使用资源名词,且使用名词的复数形式,例如:

URL			请求类型			      	说明
/v2/users		GET					获取用户列表
/v2/users	 	POST				     添加用户
/v2/users 	 	PUT					修改用户
/v2/users/{id}  	GET					根据id获取用户
/v2/users/{id}	     DELETE				     根据id删除用户
/v2/users/{id}  	PUT					根据id修改用户

3、服务器响应时返回JSON对象,应包含HTTP状态码、消息、结果等,如:

{
  "code": 1,
  "msg": "请求成功",
  "data": {
    "id": 1,
    "username": "qzcsbj1",
    "password": "62f7f5673e94eca261b8fce7ae7863a4",
    "realName": "qzcsbj1",
    "sex": "男",
    "birthday": "2018-09-06",
    "phone": "13800000001",
    "utype": "0",
    "addtime": "2023-01-01 11:24:49.0",
    "adduser": "qzcsbj"
  }
}

  

Restful API开发:CRUD

数据库表

SET FOREIGN_KEY_CHECKS=0;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(20) NOT NULL COMMENT '用户名',
  `password` varchar(255) NOT NULL COMMENT '密码',
  `real_name` varchar(255) NOT NULL COMMENT '真实名',
  `sex` varchar(255) DEFAULT NULL COMMENT '性别',
  `birthday` date DEFAULT NULL COMMENT '生日',
  `phone` varchar(255) NOT NULL COMMENT '电话',
  `utype` tinyint(1) DEFAULT NULL COMMENT '用户类型',
  `addtime` datetime DEFAULT NULL COMMENT '添加时间',
  `adduser` varchar(255) DEFAULT NULL COMMENT '添加者',
  PRIMARY KEY (`id`),
  UNIQUE KEY `phone` (`phone`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

  

实体类

package com.qzcsbj.demo.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.Date;

/**
 * @公众号 : 全栈测试笔记
 * @博客 : www.cnblogs.com/uncleyong
 * @微信 : ren168632201
 * @描述 : <>
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
    private static final long serialVersionUID = 5753660691492463802L;

    private Integer id;  // 实体类推荐用包装类
    private String username;
    private String password;
    private String realName;
    private String sex;
    private Date birthday;
    private String phone;
    private String utype;
    private String addtime;
    private String adduser;
}

  

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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.qzcsbj.demo</groupId>
    <artifactId>springbootdemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springbootdemo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.18</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

 

配置

application.properties

spring.profiles.active=test

  

application-test.properties

# 测试环境
server.port=8082

# 配置数据库的连接信息
spring.datasource.url=jdbc:mysql://192.168.117.180:3306/gift?useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.username=root
spring.datasource.password=qzcsbj
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

# 指定Mapper.xml的位置
mybatis.mapper-locations=classpath:mappers/*.xml
# 给实体类取别名
mybatis.type-aliases-package=com.qzcsbj.demo.pojo

 

mapper接口:UserMapper

package com.qzcsbj.demo.mapper;

import com.qzcsbj.demo.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;

/**
 * @公众号 : 全栈测试笔记
 * @博客 : www.cnblogs.com/uncleyong
 * @微信 : ren168632201
 * @描述 : <>
 */
@Mapper
public interface UserMapper {
    // restful api:增、删、改、查
    int add(User user);
    int delete(Integer id);
    int update(User user);
    User findById(Integer id);
    List<User> findAll();
}

 

xml映射文件(resources下的mappers目录中:UserMapper.xml)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qzcsbj.demo.mapper.UserMapper">
    <resultMap id="userMap" type="com.qzcsbj.demo.pojo.User">
        <id column="id" property="id"/>
        <result column="real_name" property="realName"/>
    </resultMap>

    <!--restful api:增-->
    <insert id="add" parameterType="User">
        insert into user values(null,#{username},#{password},#{realName},#{sex},#{birthday},#{phone},#{utype},now(),#{adduser})
    </insert>

    <!--restful api:删-->
    <delete id="delete">
        delete from user where id=#{id}
    </delete>

    <!--restful api:改-->
    <update id="update">
        update user set username=#{username},password=#{password},real_name=#{realName},sex=#{sex},birthday=#{birthday},phone=#{phone},utype=#{utype},adduser=#{adduser}
        where id=#{id}
    </update>


    <!--restful api:查-->
    <select id="findById" resultMap="userMap">
         select * from user where id=#{id}
    </select>

    <!--restful api:查所有-->
    <select id="findAll" resultMap="userMap">
        select * from user
    </select>

</mapper>

  

service层接口:UserService

package com.qzcsbj.demo.service;

import com.qzcsbj.demo.pojo.User;

import java.util.List;

/**
 * @公众号 : 全栈测试笔记
 * @博客 : www.cnblogs.com/uncleyong
 * @微信 : ren168632201
 * @描述 : <>
 */
public interface UserService {
    // restful api:增、删、改、查、查所有
    int add(User user);
    int delete(Integer id);
    int update(User user);
    User findById(Integer id);
    List<User> findAll();
}

  

service层实现类:UserServiceImpl

package com.qzcsbj.demo.service.impl;

import com.qzcsbj.demo.mapper.UserMapper;
import com.qzcsbj.demo.pojo.User;
import com.qzcsbj.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @公众号 : 全栈测试笔记
 * @博客 : www.cnblogs.com/uncleyong
 * @微信 : ren168632201
 * @描述 : <>
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    // restful api:增
    @Override
    public int add(User user) {
        return userMapper.add(user);
    }

    // restful api:删
    @Override
    public int delete(Integer id) {
        return userMapper.delete(id);
    }

    // restful api:改
    @Override
    public int update(User user) {
        return userMapper.update(user);
    }

    // restful api:查
    @Override
    public User findById(Integer id) {
        return userMapper.findById(id);
    }

    // restful api:查所有
    @Override
    public List<User> findAll() {
        return userMapper.findAll();
    }
}

  

controller层

package com.qzcsbj.demo.controller;

import com.qzcsbj.demo.commons.ResultCode;
import com.qzcsbj.demo.commons.ResultCommon;
import com.qzcsbj.demo.mapper.UserMapper;
import com.qzcsbj.demo.pojo.User;
import com.qzcsbj.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;

/**
 * @公众号 : 全栈测试笔记
 * @博客 : www.cnblogs.com/uncleyong
 * @微信 : ren168632201
 * @描述 : <>
 */
@RestController
@RequestMapping("/v2")
public class UserController {
    @Autowired
    UserService userService;

    // restful api:增
    @PostMapping("/users")
    public ResultCommon add(User user){
        int n = userService.add(user);
        if (n>0){
            return ResultCommon.success(ResultCode.SUCCESS);
        } else {
            return ResultCommon.fail(ResultCode.FAIL);
        }
    }

    // restful api:删
    @DeleteMapping("/users/{id}")
    public ResultCommon delete(@PathVariable("id") Integer id){
        int n = userService.delete(id);
        if (n>0){
            return ResultCommon.success(ResultCode.SUCCESS);
        } else {
            return ResultCommon.fail(ResultCode.FAIL);
        }
    }

    // restful api:改
    @PutMapping("/users")
    public ResultCommon update(User user){
        int n = userService.update(user);
        if (n>0){
            return ResultCommon.success(ResultCode.SUCCESS);
        } else {
            return ResultCommon.fail(ResultCode.FAIL);
        }
    }

    // restful api:查
    @GetMapping("/users/{id}")
    // @RequestMapping(value = "/user/{id}", method=RequestMethod.GET)
    public ResultCommon findById(@PathVariable("id") Integer id){
        User user = userService.findById(id);
        return ResultCommon.success(ResultCode.SUCCESS, user);
    }

    // restful api:查所有
    @GetMapping("/users")
    public ResultCommon findAll(){
        List<User> users = userService.findAll();
        return ResultCommon.success(ResultCode.SUCCESS, users);
    }
}

 

jmeter测试Restful API

http请求默认值

ip、端口

 

 

 

 

 

 

 

上图是修改前

 

 

修改后

 

 

 

查所有

 

 

 

【bak】

原文会持续更新,原文地址:https://www.cnblogs.com/uncleyong/p/17065905.html

 

posted @ 2023-01-24 12:28  全栈测试笔记  阅读(395)  评论(0编辑  收藏  举报
浏览器标题切换
浏览器标题切换end