spring-cloud-base

repository·master·Indexed 19 days ago

https://github.com/fp2952/spring-cloud-base

A microservices foundation framework based on SpringCloud and SpringBoot. It provides a scaffold for rapid development featuring OAuth2 authorization, an API gateway, and basic data management modules. The project includes an Authorization Center (auth-center), API Gateway (api-gateway), a Basic Data Center/Resource Server (main-data), and a Vue.js-based client application (web-app). It supports deployment via Docker and docker-compose, utilizing Consul for service discovery, MySQL for relational data, and Redis for caching.

Tokens
5.4K
Snippets
19
Records
24
Agent score
65%

What's inside spring-cloud-base

  1. Overview of spring-cloud-base

    master

    spring-cloud-base is a microservices foundation framework developed using SpringCloud and SpringBoot. It provides a scaffold for rapid microservice development, featuring:

    • Unified Authorization & Authentication: Uses OAuth2 for security.
    • Core Modules: Includes an Authorization Center (auth-center), an API Gateway (api-gateway), and a Basic Data Center/Resource Server (main-data).
    • Client Application: A Vue.js-based OAuth2 example client for user, resource, and role management.
    • Deployment: Supports rapid deployment via Docker and docker-compose.

    Demo Credentials:

  2. Quick Start: Manual Setup and Execution

    master

    To run the project manually, follow these steps:

    1. Prerequisites

    Ensure you have the following installed:

    • JDK 8, Maven, Node.js
    • MySQL, Redis, Consul, RabbitMQ

    2. Setup Steps

    1. Clone the repository: git clone https://github.com/fp2952/spring-cloud-base.git
    2. Initialize Database: Run the main-data/schema.sql file in your MySQL instance.
    3. Configure Environment: Update the configuration files in config-git/src/main/resource/config (specifically database, Redis, and RabbitMQ connection strings).
    4. Start Consul: Run consul agent -dev. Access the UI at http://localhost:8500.
    5. Start Infrastructure: Start Redis and RabbitMQ.
    6. Start Microservices (Follow this specific order):
      • Config Server: config-git/ConfigServerApplication.main (Must start first).
      • Authorization Center: auth-center/auth-center-provider/AuthCenterProviderApplication.main.
      • API Gateway: api-gateway/ApiGatewayApplication.main.
      • Basic Data Module: main-data/main-data-provider/MainDataApplication.main. (Note: Gateway and Basic Data modules depend on the Authorization Center's JWT/key-uri point).

    3. Start Frontend

    1. Navigate to the web app: cd web-app
    2. Install dependencies: npm install
    3. Run the project: npm dev run
    4. Important: Update the backend API address in /static/config.js under window.serverconf.development.
    # Clone
    git clone https://github.com/fp2952/spring-cloud-base.git
    
    # Frontend setup
    cd web-app
    npm install
    npm dev run
  3. Build and run the web-app project

    master

    The web-app is a Vue.js project. You can manage its lifecycle using the following npm scripts:

    • Install dependencies: Run npm install to download required packages.
    • Development mode: Run npm run dev to start a local development server with hot reload enabled at http://localhost:8080.
    • Production build: Run npm run build to create a minified production bundle.
    • Analyze bundle: Run npm run build --report to generate a production build and view a bundle analyzer report to inspect asset sizes.
    # install dependencies
    npm install
    
    # serve with hot reload at localhost:8080
    npm run dev
    
    # build for production with minification
    npm run build
    
    # build for production and view the bundle analyzer report
    npm run build --report
  4. Quick Start: Deployment via docker-compose

    master

    You can deploy the entire stack using Docker and docker-compose.

    1. Build Images

    First, use Maven to build the backend services using the docker-maven-plugin:

    # Build backend services (auth-center-provider, main-data-provider, api-gateway)
    mvn clean
    mvn package docker:build

    Then, build the frontend Node.js application image:

    cd /spring-cloud-base/web-app
    docker build -t node-app .

    2. Configure docker-compose.yml

    Update the node-app section in docker-compose.yml with your host IP and the correct ports. The BASE_URL should be the Host IP and the port mapped to the container for OAuth2 redirects.

    3. Run

    cd /spring-cloud-base/docker-compose
    docker-compose up [-d]
    # Build backend
    mvn clean
    mvn package docker:build
    
    # Build frontend
    cd /spring-cloud-base/web-app
    docker build -t node-app .
    
    # Run stack
    cd /spring-cloud-base/docker-compose
    docker-compose up -d
  5. Configure the Spring Cloud Base environment with Docker Compose

    master

    The project provides a docker-compose.yml file to orchestrate the entire microservices stack, including service discovery (Consul), authentication (auth-center), API Gateway, data services, and a Node.js frontend application.

    Service Overview

    • consul: Service discovery and configuration.
    • auth-center: The authorization center provider.
    • api-gateway: The entry point for backend API calls.
    • main-data: The primary data provider service.
    • mysql: Relational database.
    • redis: In-memory data store.
    • node-app: The frontend/client application.

    Port Mapping Summary

    ServiceHost PortDescription
    api-gateway18000Backend API Gateway
    auth-center18001Authorization service
    main-data18002Main data service
    mysql3306MySQL database
    redis6379Redis cache
    node-app8080Frontend application
    docker-compose up
  6. Initialize the Vue application entry point

    master

    The application is initialized by mounting a new Vue instance to the #app element. The setup process involves registering several core plugins and configuration modules:

    1. ElementUI: Integrated with a custom i18n translation function for component messages.
    2. Auth Client: The Auth plugin is registered using Vue.use(Auth, router), which links authentication logic to the Vue Router.
    3. Config: The Config module is initialized via Config.init(Vue) to make configuration available globally.
    4. Core Modules: The instance uses router, store (Vuex), and i18n (Internationalization) plugins.

    Ensure that the #app element exists in your HTML template before the application mounts.

    import Vue from 'vue'
    import App from './App'
    import router from './router'
    import Auth from './plugin/auth-client'
    import store from './store'
    import ElementUI from 'element-ui'
    import 'element-ui/lib/theme-chalk/index.css'
    import i18n from './plugin/i18n'
    import Config from './config/config'
    import '@/assets/fonts/iconfont.css'
    
    Vue.config.productionTip = false
    
    Vue.use(ElementUI, {
      i18n: (key, value) => i18n.t(key, value)
    })
    Vue.use(Auth, router)
    Config.init(Vue)
    
    new Vue({
      el: '#app',
      router,
      store,
      i18n,
      components: { App },
      template: '<App/>'
    })
  7. Install the auth-client plugin in Vue

    master

    The auth-client plugin can be installed into a Vue application to provide authentication routing and global authentication utilities. During installation, it initializes the AuthRouter and attaches an $auth object to the Vue.prototype.

    To use it, pass the Vue constructor and the Router instance to the install method of the plugin.

    import Vue from 'vue';
    import Router from './router';
    import AuthClient from './plugin/auth-client';
    
    Vue.use(AuthClient, Router);
  8. Configure production build settings

    master

    The build object defines how the application is compiled for production. Key options include:

    • assetsRoot: The output directory for the build (default: ../dist).
    • assetsSubDirectory: The directory for static assets (default: 'static').
    • assetsPublicPath: The base path for assets (default: '/').
    • productionSourceMap: Whether to generate source maps for production.
    • devtool: The production source map type (default: '#source-map').
    • productionGzip: Enables Gzip compression (requires compression-webpack-plugin).
    • productionGzipExtensions: File extensions to compress (default: ['js', 'css']).
    • bundleAnalyzerReport: Enables the bundle analyzer report if triggered via CLI.
    build: {
      index: path.resolve(__dirname, '../dist/index.html'),
      assetsRoot: path.resolve(__dirname, '../dist'),
      assetsSubDirectory: 'static',
      assetsPublicPath: '/',
      productionSourceMap: true,
      devtool: '#source-map',
      productionGzip: false,
      productionGzipExtensions: ['js', 'css'],
      bundleAnalyzerReport: process.env.npm_config_report
    }
  9. Configure api-gateway environment variables

    master

    The api-gateway service requires the following environment variables to connect to service discovery and the authentication center:

    • CONSUL_HOST: Hostname of the Consul service (default: consul).
    • CONSUL_PORT: Port of the Consul service (default: 8500).
    • AUTH_CENTER_HOST: Hostname of the auth-center service (default: auth-center).
    • AUTH_CENTER_PORT: Port of the auth-center service (default: 18001).
  10. Configure development environment settings

    master

    The dev object in the configuration file controls the behavior of the local development server. Key options include:

    • assetsSubDirectory: The directory for static assets (default: 'static').
    • assetsPublicPath: The base path for assets (default: '/').
    • host: The host address for the dev server (default: 'localhost').
    • port: The port for the dev server (default: 8080).
    • autoOpenBrowser: Whether to automatically open the browser on startup.
    • useEslint: Enables linting during bundling.
    • devtool: Controls source map generation (default: 'cheap-module-eval-source-map').
    • cacheBusting: Helps with debugging Vue files in devtools.
    dev: {
      assetsSubDirectory: 'static',
      assetsPublicPath: '/',
      proxyTable: {
        '/api': {
          target: 'http://127.0.0.1:18000',
          changeOrigin: true
        }
      },
      host: 'localhost',
      port: 8080,
      autoOpenBrowser: false,
      errorOverlay: true,
      notifyOnErrors: true,
      poll: false,
      useEslint: true,
      showEslintErrorsInOverlay: false,
      devtool: 'cheap-module-eval-source-map',
      cacheBusting: true,
      cssSourceMap: true
    }
  11. Configure the development server proxy

    master

    In development mode, you can configure a proxy to avoid CORS issues when communicating with backend services. The proxyTable object allows you to map specific URL paths to a target server.

    For example, to route all requests starting with /api to a local backend running on port 18000, use the following configuration. Setting changeOrigin: true is required to ensure the request headers match the target server's rules (e.g., Access-Control-Allow-Origin).

    proxyTable: {
      '/api': {
        target: 'http://127.0.0.1:18000',
        changeOrigin: true
      }
    }
  12. Configure Vue-i18n internationalization plugin

    master

    The web-app package uses vue-i18n to manage multi-language support. The plugin automatically detects the user's browser language via navigator.language (or navigator.userLanguage) and selects a two-letter language code.

    Supported locales:

    • Chinese: Mapped to the zh language code.
    • English: Mapped to any other language code.

    The configuration exports a singleton instance of VueI18n containing the loaded translation messages from @/assets/translate/Chinese and @/assets/translate/English.

    import VueI18n from 'vue-i18n'
    import {Ch} from '@/assets/translate/Chinese'
    import {En} from '@/assets/translate/English'
    
    // The exported instance is configured as follows:
    export default new VueI18n({
      locale: lang === 'zh' ? 'Chinese' : 'English',
      messages: {
        Chinese: Ch,
        English: En
      }
    })