互联网技术IT交流圈

Spring Boot 第一个项目-helloWorld

2019-01-22  本文已影响77人  牵手生活

环境准备

idea配置导入源码

简单应用

场景说明

【Tip】Spring WebFlux应用程序并不严格依赖于Servlet API,因此它们不能作为war文件部署,也不能使用该src/main/webapp目录。

第一步:start.spring.io 构建应用,并下载

https://start.spring.io/
spring boot 项目信息 spring boot 配置选项

第2步:用idea导入Gradle项目(start.spring.io 构建的zip,解压)

第一步start.spring.io 构建的zip,解压到指定目录后,用idea导入

idea 导入gradle项目 idea导入后的目录结构

导入过程碰到的问题及解决办法:


idea导入spring boot 碰到问题

使用idea导入springboot项目maven报错Non-managed pom.xml file found

https://blog.csdn.net/q89757316/article/details/80896382

IDEA中Spring Boot的@SpringBootApplication无法引入的问题

https://blog.csdn.net/weixin_41942804/article/details/80044101


第3步:编写代码

项目的结构


项目结构

3-1 创建用户模型:User

/**
 * 用户模型
 *
 */
public class User {
    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

创建用户仓储:UserRepostory

package com.younghare.springBoothelloworld.repository;

import org.springframework.stereotype.Repository;
import com.younghare.springBoothelloworld.domain.User;

import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * {@link User} {@link Repository}
 */
@Repository
public class UserRepostory {
    /**
     * 采用内存型存储方式 -> Map
     */

    private final ConcurrentMap<Integer,User> repository = new ConcurrentHashMap<>();

    private final static AtomicInteger idGenerator =
            new AtomicInteger();

    /**
     * 保存用户对象
     * @param user {@link User} 对象
     * @return 如果保存成功,返回<code>true</code>,否则返回<code>false</code>
     */
    public boolean save(User user){
        boolean success = false;

        Integer id = idGenerator.incrementAndGet();
        //repository.put(id,user);
        user.setId(id);

        return  repository.put(id,user) == null;

    }

    public Collection<User> findAll(){
        return repository.values();
    }
}


3-3创建用户控制器:UserController

package com.younghare.springBoothelloworld.controller;

import com.younghare.springBoothelloworld.domain.User;
import com.younghare.springBoothelloworld.repository.UserRepostory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController  //表示是一个Rest接口
public class UserController {

    private  final UserRepostory userRepostory;  //没有初始化,这里采用构造器注入的方式

    @Autowired
    public UserController(UserRepostory userRepostory){
        this.userRepostory = userRepostory;

    }

    @PostMapping("/person/save")
    public User save(@RequestParam String name){

        User user = new User();
        user.setName(name);
        if (userRepostory.save(user)){
            System.out.printf("用户对象:%s 保存成功\n",user);
        }
        return user;
    }

}

第4步:用idea进行debug运行、调试

可以看到运行的行程pid


idea 中debug运行调试 log上看到的pid和任务管理器的pid一致

看到webapi的接口及端口号

webapi的接口及端口号 日志上有看到是用Netty 服务的8080端口

第5步:用Postman发送Post请求---添加用户--添加的用户存储在Map内存中

localhost:8080/person/save

在postman中添加地址及post参数

Postman发送Post请求、及断点情况

post添加用户请求,添加的用户存储在Map内存中

第6步:编写路由器函数 配置:RouteFunctionConfiguration


/**
 * 路由器函数 配置
 */
@Configuration
public class RouteFunctionConfiguration {
    /**
     * Servlet
     *  请求接口:ServletRequet 或者 HttpServletRequest
     *  响应接口:ServletResponse 或者 HttpServletResponse
     *
     *  Spring 5.0重新定义了服务请求和响应接口
     *  请求接口 :ServerRequest
     *  响应接口 :ServerResponse
     *  即可支持Servlet规范,也可以支持自定义,比如Netty (Web Server)
     *
     *  以本例:
     *  定义GET请求,并且返回所以的用户对象 URI:/person/find/all
     *
     *  Flux 是0--n个对象集合
     *  Mono 是0--1个对象集合
     *  Reactive 中的Flux或Mone它是异步处理(非阻塞式)
     *  集合对象基本上是同步处理(阻塞式)
     *
     *  Flux或者Mono 都是Publisher
     */

    @Bean
    @Autowired  //方法参数注入
    public RouterFunction<ServerResponse> personFindAll(UserRepostory userRepostory){



       return RouterFunctions.route(RequestPredicates.GET("/person/find/all"),
                request -> {

                    //返回所有的用户对象
                    Collection<User> users = userRepostory.findAll();
                    Mono<ServerResponse> response = null;
                    Flux<User> userFlux =Flux.fromIterable(users);  //把Collection对象转换为Flux对象

                    return ServerResponse.ok().body(userFlux,User.class);


                }
                );

    }
}

关于Spring WebFlux) 参考官方文档

https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html
Spring -Web Flux的官网文档

第7步:重新debug模式运行项目

看到路由配置信息

安装前面的Post方式提交多次添加用户请求,让Map中有多个用户数据
用Postman发送查询

localhost:8080/person/find/all
路由断点情况 postman上看到的查询结果

其他查阅资料

Flux简介-Flux是Facebook用于构建客户端Web应用程序的一个系统架构
Spring Webflux
Spring WebFlux快速上手——响应式Spring的道法术器
Springboot2.0中webflux到底优秀在哪里--优秀
SpringBoot 2.0 Webflux 介绍 和Demo示例
spring5.0 函数式web框架 webflux
Flux 会取代 Web MVC,或可不再基于 Servlet 容器了?

上一篇 下一篇

猜你喜欢

热点阅读