3、Hyperf 3 微服务系列 - 构建 note web 应用项目

作者: 温新

分类: 【Hyperf 3 微服务系列】

阅读: 945

时间: 2023-05-13 11:36:25

hi,我是温新,一名 PHPer

Hyperf 3 微服务代码已上传至 Github:https://github.com/ziruchu/hyperf3-microservice-code

本系列将使用一个用户笔记项目来学习微服务。在此之前保证你的环境已安装完成。

环境说明

系统:Rocky Linux 9.1
PHP: 8.2.3
Swoole:5.0.2

构建笔记项目

安装项目

composer create-project hyperf/hyperf-skeleton note

安装项目时,除了语言选择 y,其他全部都直接回车。

编写业务逻辑

编写业务逻辑之前,先来对业务进行说明。本次有两个业务,一个是用户业务,一个是笔记业务。

用户业务

1、创建 UserController

<?php
// app/Controller/UserController.php
    
namespace App\Controller;

use App\Service\UserService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;

#[Controller]
class UserController
{
    #[Inject]
    protected UserService $userService;

    #[GetMapping('/users/info')]
    public function getUserInfo()
    {
        return $this->userService->getUserInfo();
    }
}

2、创建 UserServer

<?php
// app/Service/UserService.php
    
namespace App\Service;

class UserService
{
    public function getUserInfo()
    {
        return '用户信息';
    }
}

用户笔记业务

1、创建 NoteController

<?php
// app/Controller/NoteController.php
namespace App\Controller;

use App\Service\NoteService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;

#[Controller]
class NoteController
{
    #[Inject]
    protected NoteService $noteService;

    #[GetMapping('/notes/info')]
    public function getNoteInfo()
    {
        return $this->noteService->getNoteInfo();
    }
}

2、创建 NoteService

<?php
// app/Service/NoteService.php
namespace App\Service;

class NoteService
{
    public function getNoteInfo()
    {
        return '笔记信息';
    }
}

运行项目

$ php bin/hyperf.php start
    
# 测试结果
$ curl http://192.168.31.90:9501/users/info
用户信息
$ curl http://192.168.31.90:9501/notes/info
笔记信息

构建服务务

从这个项目中可以看到,现在有两个业务,用户与笔记。构建微服务时,我们把用户笔记 抽离成单独的应用。

下篇文章开始,我们进入微服务学习。

请登录后再评论