简单的基于Spring Cloud和Vue的示例项目结构及部分关键代码

后端(Spring Cloud部分)

1. 创建Spring Cloud项目(以Spring Cloud Gateway和Spring Cloud Eureka为例)

首先,使用Spring Initializr创建一个基础的Spring Boot项目,并添加相关的Spring Cloud依赖,比如:

  • spring-cloud-starter-gateway:用于实现API网关功能。
  • spring-cloud-starter-netflix-eureka-server(如果搭建注册中心的话):用于服务注册与发现。

pom.xml示例片段(部分依赖)

<?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-parent</artifactId>
        <version>2.7.13</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>spring-cloud-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-cloud-demo</name>
    <description>Demo project for Spring Cloud</description>
    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>2021.0.6</spring-cloud.version>
    </properties>
    <dependencies>
        <!-- Eureka Server依赖 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
        <!-- Gateway依赖 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

2. 配置Eureka Server(服务注册中心,可选,如果有多个微服务需要互相发现的话)

创建一个启动类并添加@EnableEurekaServer注解来开启Eureka服务:

EurekaServerApplication.java

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }
}

再配置application.yml文件:

server:
  port: 8761
eureka:
  instance:
    hostname: localhost
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

3. 创建微服务(以一个简单的用户服务为例)

创建一个Spring Boot项目作为用户微服务,添加spring-cloud-starter-netflix-eureka-client依赖用于注册到Eureka Server(如果使用了的话)。

pom.xml(用户服务部分)

<?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-parent</artifactId>
        <version>2.7.13</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>user-service</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>user-service</name>
    <description>User Service in Spring Cloud</description>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

创建一个简单的用户实体类:

User.java

import java.io.Serializable;

public class User implements Serializable {
    private Long id;
    private String username;
    private String password;

    // 构造函数、Getter和Setter方法等
    public User() {
    }

    public User(Long id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    // Getter和Setter
    public Long getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

然后创建一个用户服务的Controller类来提供接口:

UserController.java

import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {
    // 模拟数据库存储用户数据
    private List<User> userList = new ArrayList<>();

    // 获取所有用户
    @GetMapping
    public List<User> getUsers() {
        return userList;
    }

    // 根据ID获取用户
    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        for (User user : userList) {
            if (user.getId() == id) {
                return user;
            }
        }
        return null;
    }

    // 创建用户
    @PostMapping
    public User createUser(@RequestBody User user) {
        userList.add(user);
        return user;
    }
}

配置application.yml文件(如果注册到Eureka):

spring:
  application:
    name: user-service
server:
  port: 8081
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

4. 配置Spring Cloud Gateway

在之前的Spring Cloud项目(包含Gateway的那个)中配置路由规则等,例如:

application.yml(Gateway配置部分)

server:
  port: 8080
spring:
  cloud:
    gateway:
      routes:
        - id: user-service-route
          uri: lb://user-service
          predicates:
            - Path=/user-service/**
          filters:
            - StripPrefix=1

这表示将路径以/user-service/开头的请求路由到名为user-service的服务(通过负载均衡,这里是简单示例),并且去掉前缀再转发。

前端(Vue部分)

1. 创建Vue项目

首先,确保已经安装了Node.js和npm(Node包管理器),然后使用vue-cli来创建一个Vue项目:

vue create vue-demo

按照提示选择相关配置(比如是否使用Vue Router、Vuex等,这里简单示例可以先不选)。

2. 编写Vue组件来调用后端接口

src/components目录下创建一个UserList.vue组件来展示用户列表(示例,简单使用axios来发送HTTP请求,需要先安装axiosnpm install axios):

UserList.vue

<template>
  <div>
    <h2>用户列表</h2>
    <ul>
      <li v-for="user in users" :key="user.id">
        {{ user.username }}
      </li>
    </ul>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      users: []
    };
  },
  mounted() {
    axios.get('http://localhost:8080/user-service/users')
     .then(response => {
        this.users = response.data;
      })
     .catch(error => {
        console.log(error);
      });
  }
};
</script>

<style scoped>

</style>

3. 在src/App.vue中使用组件

修改App.vue文件来展示我们的UserList组件:

App.vue

<template>
  <div id="app">
    <UserList />
  </div>
</template>

<script>
import UserList from './components/UserList.vue';

export default {
  name: 'App',
  components: {
    UserList
  }
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

最后,运行Vue项目:

npm run serve
posted @ 2024-12-18 16:49  软件职业规划  阅读(10)  评论(0编辑  收藏  举报