Jelajahi Sumber

0807 实现书籍作者模块

Qing 9 bulan lalu
induk
melakukan
6fb716dfa5
33 mengubah file dengan 1221 tambahan dan 24 penghapusan
  1. 1 0
      novel-cloud-demo/.idea/misc.xml
  2. 19 0
      novel-cloud-demo/novel-author/.mvn/wrapper/maven-wrapper.properties
  3. 259 0
      novel-cloud-demo/novel-author/mvnw
  4. 149 0
      novel-cloud-demo/novel-author/mvnw.cmd
  5. 59 0
      novel-cloud-demo/novel-author/pom.xml
  6. 18 0
      novel-cloud-demo/novel-author/src/main/java/com/sf/author/NovelAuthorApplication.java
  7. 49 0
      novel-cloud-demo/novel-author/src/main/java/com/sf/author/config/TokenInterceptor.java
  8. 20 0
      novel-cloud-demo/novel-author/src/main/java/com/sf/author/config/WebConfig.java
  9. 65 0
      novel-cloud-demo/novel-author/src/main/java/com/sf/author/controller/AuthorInfoController.java
  10. 59 0
      novel-cloud-demo/novel-author/src/main/java/com/sf/author/dto/req/AuthorRegisterReqDto.java
  11. 83 0
      novel-cloud-demo/novel-author/src/main/java/com/sf/author/entity/AuthorInfo.java
  12. 16 0
      novel-cloud-demo/novel-author/src/main/java/com/sf/author/mapper/AuthorInfoMapper.java
  13. 24 0
      novel-cloud-demo/novel-author/src/main/java/com/sf/author/service/IAuthorInfoService.java
  14. 70 0
      novel-cloud-demo/novel-author/src/main/java/com/sf/author/service/impl/AuthorInfoServiceImpl.java
  15. 37 0
      novel-cloud-demo/novel-author/src/main/java/com/sf/author/util/JwtUtils.java
  16. 22 0
      novel-cloud-demo/novel-author/src/main/java/com/sf/author/util/UserHolder.java
  17. 12 0
      novel-cloud-demo/novel-author/src/main/resources/application.yml
  18. 6 0
      novel-cloud-demo/novel-author/src/main/resources/bootstrap.yml
  19. 5 0
      novel-cloud-demo/novel-author/src/main/resources/mapper/AuthorInfoMapper.xml
  20. 16 0
      novel-cloud-demo/novel-author/src/test/java/com/sf/author/NovelAuthorApplicationTests.java
  21. 4 0
      novel-cloud-demo/novel-book/novel-book-api/src/main/java/com/sf/book/client/BookFeign.java
  22. 23 0
      novel-cloud-demo/novel-book/novel-book-api/src/main/java/com/sf/book/client/dto/BookPageReqDto.java
  23. 6 0
      novel-cloud-demo/novel-book/novel-book-api/src/main/java/com/sf/book/client/fallback/BookFeignFallback.java
  24. 23 4
      novel-cloud-demo/novel-book/novel-book-service/src/main/java/com/sf/book/controller/BookChapterController.java
  25. 13 0
      novel-cloud-demo/novel-book/novel-book-service/src/main/java/com/sf/book/controller/inner/InnerBookController.java
  26. 23 0
      novel-cloud-demo/novel-book/novel-book-service/src/main/java/com/sf/book/dto/inner/BookPageReqDto.java
  27. 12 0
      novel-cloud-demo/novel-book/novel-book-service/src/main/java/com/sf/book/service/IAuthorBookService.java
  28. 16 0
      novel-cloud-demo/novel-book/novel-book-service/src/main/java/com/sf/book/service/IBookChapterService.java
  29. 49 0
      novel-cloud-demo/novel-book/novel-book-service/src/main/java/com/sf/book/service/impl/AuthorBookServiceImpl.java
  30. 44 0
      novel-cloud-demo/novel-book/novel-book-service/src/main/java/com/sf/book/service/impl/BookChapterServiceImpl.java
  31. 10 18
      novel-cloud-demo/novel-core/src/main/java/com/sf/core/util/GeneUtils.java
  32. 6 0
      novel-cloud-demo/novel-gateway/src/main/resources/application.yml
  33. 3 2
      novel-cloud-demo/pom.xml

+ 1 - 0
novel-cloud-demo/.idea/misc.xml

@@ -11,6 +11,7 @@
         <option value="$PROJECT_DIR$/novel-gateway/pom.xml" />
         <option value="$PROJECT_DIR$/novel-news/pom.xml" />
         <option value="$PROJECT_DIR$/novel-user/novel-user-service/pom.xml" />
+        <option value="$PROJECT_DIR$/novel-author/pom.xml" />
       </list>
     </option>
   </component>

+ 19 - 0
novel-cloud-demo/novel-author/.mvn/wrapper/maven-wrapper.properties

@@ -0,0 +1,19 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+wrapperVersion=3.3.2
+distributionType=only-script
+distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.7/apache-maven-3.9.7-bin.zip

+ 259 - 0
novel-cloud-demo/novel-author/mvnw

@@ -0,0 +1,259 @@
+#!/bin/sh
+# ----------------------------------------------------------------------------
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#    https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+# ----------------------------------------------------------------------------
+
+# ----------------------------------------------------------------------------
+# Apache Maven Wrapper startup batch script, version 3.3.2
+#
+# Optional ENV vars
+# -----------------
+#   JAVA_HOME - location of a JDK home dir, required when download maven via java source
+#   MVNW_REPOURL - repo url base for downloading maven distribution
+#   MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
+#   MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
+# ----------------------------------------------------------------------------
+
+set -euf
+[ "${MVNW_VERBOSE-}" != debug ] || set -x
+
+# OS specific support.
+native_path() { printf %s\\n "$1"; }
+case "$(uname)" in
+CYGWIN* | MINGW*)
+  [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
+  native_path() { cygpath --path --windows "$1"; }
+  ;;
+esac
+
+# set JAVACMD and JAVACCMD
+set_java_home() {
+  # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
+  if [ -n "${JAVA_HOME-}" ]; then
+    if [ -x "$JAVA_HOME/jre/sh/java" ]; then
+      # IBM's JDK on AIX uses strange locations for the executables
+      JAVACMD="$JAVA_HOME/jre/sh/java"
+      JAVACCMD="$JAVA_HOME/jre/sh/javac"
+    else
+      JAVACMD="$JAVA_HOME/bin/java"
+      JAVACCMD="$JAVA_HOME/bin/javac"
+
+      if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
+        echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
+        echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
+        return 1
+      fi
+    fi
+  else
+    JAVACMD="$(
+      'set' +e
+      'unset' -f command 2>/dev/null
+      'command' -v java
+    )" || :
+    JAVACCMD="$(
+      'set' +e
+      'unset' -f command 2>/dev/null
+      'command' -v javac
+    )" || :
+
+    if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
+      echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
+      return 1
+    fi
+  fi
+}
+
+# hash string like Java String::hashCode
+hash_string() {
+  str="${1:-}" h=0
+  while [ -n "$str" ]; do
+    char="${str%"${str#?}"}"
+    h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
+    str="${str#?}"
+  done
+  printf %x\\n $h
+}
+
+verbose() { :; }
+[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
+
+die() {
+  printf %s\\n "$1" >&2
+  exit 1
+}
+
+trim() {
+  # MWRAPPER-139:
+  #   Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
+  #   Needed for removing poorly interpreted newline sequences when running in more
+  #   exotic environments such as mingw bash on Windows.
+  printf "%s" "${1}" | tr -d '[:space:]'
+}
+
+# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
+while IFS="=" read -r key value; do
+  case "${key-}" in
+  distributionUrl) distributionUrl=$(trim "${value-}") ;;
+  distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
+  esac
+done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties"
+[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties"
+
+case "${distributionUrl##*/}" in
+maven-mvnd-*bin.*)
+  MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
+  case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
+  *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
+  :Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
+  :Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
+  :Linux*x86_64*) distributionPlatform=linux-amd64 ;;
+  *)
+    echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
+    distributionPlatform=linux-amd64
+    ;;
+  esac
+  distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
+  ;;
+maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
+*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
+esac
+
+# apply MVNW_REPOURL and calculate MAVEN_HOME
+# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
+[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
+distributionUrlName="${distributionUrl##*/}"
+distributionUrlNameMain="${distributionUrlName%.*}"
+distributionUrlNameMain="${distributionUrlNameMain%-bin}"
+MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
+MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
+
+exec_maven() {
+  unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
+  exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
+}
+
+if [ -d "$MAVEN_HOME" ]; then
+  verbose "found existing MAVEN_HOME at $MAVEN_HOME"
+  exec_maven "$@"
+fi
+
+case "${distributionUrl-}" in
+*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
+*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
+esac
+
+# prepare tmp dir
+if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
+  clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
+  trap clean HUP INT TERM EXIT
+else
+  die "cannot create temp dir"
+fi
+
+mkdir -p -- "${MAVEN_HOME%/*}"
+
+# Download and Install Apache Maven
+verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
+verbose "Downloading from: $distributionUrl"
+verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
+
+# select .zip or .tar.gz
+if ! command -v unzip >/dev/null; then
+  distributionUrl="${distributionUrl%.zip}.tar.gz"
+  distributionUrlName="${distributionUrl##*/}"
+fi
+
+# verbose opt
+__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
+[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
+
+# normalize http auth
+case "${MVNW_PASSWORD:+has-password}" in
+'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
+has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
+esac
+
+if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
+  verbose "Found wget ... using wget"
+  wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
+elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
+  verbose "Found curl ... using curl"
+  curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
+elif set_java_home; then
+  verbose "Falling back to use Java to download"
+  javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
+  targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
+  cat >"$javaSource" <<-END
+	public class Downloader extends java.net.Authenticator
+	{
+	  protected java.net.PasswordAuthentication getPasswordAuthentication()
+	  {
+	    return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
+	  }
+	  public static void main( String[] args ) throws Exception
+	  {
+	    setDefault( new Downloader() );
+	    java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
+	  }
+	}
+	END
+  # For Cygwin/MinGW, switch paths to Windows format before running javac and java
+  verbose " - Compiling Downloader.java ..."
+  "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
+  verbose " - Running Downloader.java ..."
+  "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
+fi
+
+# If specified, validate the SHA-256 sum of the Maven distribution zip file
+if [ -n "${distributionSha256Sum-}" ]; then
+  distributionSha256Result=false
+  if [ "$MVN_CMD" = mvnd.sh ]; then
+    echo "Checksum validation is not supported for maven-mvnd." >&2
+    echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
+    exit 1
+  elif command -v sha256sum >/dev/null; then
+    if echo "$distributionSha256Sum  $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then
+      distributionSha256Result=true
+    fi
+  elif command -v shasum >/dev/null; then
+    if echo "$distributionSha256Sum  $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
+      distributionSha256Result=true
+    fi
+  else
+    echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
+    echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
+    exit 1
+  fi
+  if [ $distributionSha256Result = false ]; then
+    echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
+    echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
+    exit 1
+  fi
+fi
+
+# unzip and move
+if command -v unzip >/dev/null; then
+  unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
+else
+  tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
+fi
+printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url"
+mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
+
+clean || :
+exec_maven "$@"

+ 149 - 0
novel-cloud-demo/novel-author/mvnw.cmd

@@ -0,0 +1,149 @@
+<# : batch portion
+@REM ----------------------------------------------------------------------------
+@REM Licensed to the Apache Software Foundation (ASF) under one
+@REM or more contributor license agreements.  See the NOTICE file
+@REM distributed with this work for additional information
+@REM regarding copyright ownership.  The ASF licenses this file
+@REM to you under the Apache License, Version 2.0 (the
+@REM "License"); you may not use this file except in compliance
+@REM with the License.  You may obtain a copy of the License at
+@REM
+@REM    https://www.apache.org/licenses/LICENSE-2.0
+@REM
+@REM Unless required by applicable law or agreed to in writing,
+@REM software distributed under the License is distributed on an
+@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+@REM KIND, either express or implied.  See the License for the
+@REM specific language governing permissions and limitations
+@REM under the License.
+@REM ----------------------------------------------------------------------------
+
+@REM ----------------------------------------------------------------------------
+@REM Apache Maven Wrapper startup batch script, version 3.3.2
+@REM
+@REM Optional ENV vars
+@REM   MVNW_REPOURL - repo url base for downloading maven distribution
+@REM   MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
+@REM   MVNW_VERBOSE - true: enable verbose log; others: silence the output
+@REM ----------------------------------------------------------------------------
+
+@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
+@SET __MVNW_CMD__=
+@SET __MVNW_ERROR__=
+@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
+@SET PSModulePath=
+@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
+  IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
+)
+@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
+@SET __MVNW_PSMODULEP_SAVE=
+@SET __MVNW_ARG0_NAME__=
+@SET MVNW_USERNAME=
+@SET MVNW_PASSWORD=
+@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*)
+@echo Cannot start maven from wrapper >&2 && exit /b 1
+@GOTO :EOF
+: end batch / begin powershell #>
+
+$ErrorActionPreference = "Stop"
+if ($env:MVNW_VERBOSE -eq "true") {
+  $VerbosePreference = "Continue"
+}
+
+# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
+$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
+if (!$distributionUrl) {
+  Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
+}
+
+switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
+  "maven-mvnd-*" {
+    $USE_MVND = $true
+    $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
+    $MVN_CMD = "mvnd.cmd"
+    break
+  }
+  default {
+    $USE_MVND = $false
+    $MVN_CMD = $script -replace '^mvnw','mvn'
+    break
+  }
+}
+
+# apply MVNW_REPOURL and calculate MAVEN_HOME
+# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
+if ($env:MVNW_REPOURL) {
+  $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" }
+  $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')"
+}
+$distributionUrlName = $distributionUrl -replace '^.*/',''
+$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
+$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain"
+if ($env:MAVEN_USER_HOME) {
+  $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain"
+}
+$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
+$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
+
+if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
+  Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
+  Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
+  exit $?
+}
+
+if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
+  Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
+}
+
+# prepare tmp dir
+$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
+$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
+$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
+trap {
+  if ($TMP_DOWNLOAD_DIR.Exists) {
+    try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
+    catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
+  }
+}
+
+New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
+
+# Download and Install Apache Maven
+Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
+Write-Verbose "Downloading from: $distributionUrl"
+Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
+
+$webclient = New-Object System.Net.WebClient
+if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
+  $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
+}
+[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
+$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
+
+# If specified, validate the SHA-256 sum of the Maven distribution zip file
+$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
+if ($distributionSha256Sum) {
+  if ($USE_MVND) {
+    Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
+  }
+  Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
+  if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
+    Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
+  }
+}
+
+# unzip and move
+Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
+Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null
+try {
+  Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
+} catch {
+  if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
+    Write-Error "fail to move MAVEN_HOME"
+  }
+} finally {
+  try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
+  catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
+}
+
+Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"

+ 59 - 0
novel-cloud-demo/novel-author/pom.xml

@@ -0,0 +1,59 @@
+<?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>com.sf</groupId>
+		<artifactId>novel-cloud-demo</artifactId>
+		<version>1.0-SNAPSHOT</version>
+	</parent>
+
+	<groupId>com.sf</groupId>
+	<artifactId>novel-author</artifactId>
+<!--	使用springboot类型创建模块时 模块的版本是0.0.1-SNAPSHOT 而用maven类型创建时 版本是1.0-SNAPSHOT-->
+<!--	可以通过删除子模块的版本 这样会默认使用父项目的版本-->
+<!--	<version>0.0.1-SNAPSHOT</version>-->
+	<name>novel-author</name>
+	<description>novel-author</description>
+
+	<dependencies>
+		<dependency>
+			<groupId>com.sf</groupId>
+			<artifactId>novel-core</artifactId>
+			<version>${project.parent.version}</version>
+		</dependency>
+
+		<!-- 使用jwt来做用户登录信息加密和校验 -->
+		<dependency>
+			<groupId>io.jsonwebtoken</groupId>
+			<artifactId>jjwt-api</artifactId>
+		</dependency>
+		<dependency>
+			<groupId>io.jsonwebtoken</groupId>
+			<artifactId>jjwt-impl</artifactId>
+			<scope>runtime</scope>
+		</dependency>
+		<dependency>
+			<groupId>io.jsonwebtoken</groupId>
+			<artifactId>jjwt-jackson</artifactId>
+			<scope>runtime</scope>
+		</dependency>
+
+		<dependency>
+			<groupId>com.sf</groupId>
+			<artifactId>novel-book-api</artifactId>
+			<version>${parent.version}</version>
+		</dependency>
+
+	</dependencies>
+
+	<build>
+		<plugins>
+			<plugin>
+				<groupId>org.springframework.boot</groupId>
+				<artifactId>spring-boot-maven-plugin</artifactId>
+			</plugin>
+		</plugins>
+	</build>
+
+</project>

+ 18 - 0
novel-cloud-demo/novel-author/src/main/java/com/sf/author/NovelAuthorApplication.java

@@ -0,0 +1,18 @@
+package com.sf.author;
+
+import org.mybatis.spring.annotation.MapperScan;
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.cloud.openfeign.EnableFeignClients;
+
+// 指定扫描feign客户端的路径
+@MapperScan("com.sf.author.mapper")
+@EnableFeignClients(basePackages = {"com.sf.book.client"})
+@SpringBootApplication(scanBasePackages = {"com.sf"})
+public class NovelAuthorApplication {
+
+	public static void main(String[] args) {
+		SpringApplication.run(NovelAuthorApplication.class, args);
+	}
+
+}

+ 49 - 0
novel-cloud-demo/novel-author/src/main/java/com/sf/author/config/TokenInterceptor.java

@@ -0,0 +1,49 @@
+package com.sf.author.config;
+
+import com.sf.author.util.JwtUtils;
+import com.sf.author.util.UserHolder;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.stereotype.Component;
+import org.springframework.web.servlet.HandlerInterceptor;
+
+// 拦截器  要实现HandlerInterceptor接口
+// 要作为spring容器的组件
+@Component
+public class TokenInterceptor implements HandlerInterceptor {
+
+    @Autowired
+    private JwtUtils jwtUtils;
+
+    @Autowired
+    private RedisTemplate redisTemplate;
+
+    // controller执行之前
+    @Override
+    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
+        String token = request.getHeader("Authorization");
+        if (token != null && !token.equals("null")) {
+            Long uid = jwtUtils.parseToken(token, "front");
+            String tokenKey = "token_" + uid;
+            System.out.println("用拦截器解析uid: " + uid);
+            String str = (String)redisTemplate.opsForValue().get(tokenKey);
+            if(str != null) {
+                UserHolder.setUserId(uid);
+            }else {
+                // 用户登录失效
+            }
+        }
+        return HandlerInterceptor.super.preHandle(request, response, handler);
+    }
+
+    // controller执行之后
+    @Override
+    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
+//        System.out.println("controller执行完成");
+        // 使用ThreadLocal要注意 使用完需要删除数据 不然可能一直占用内存 导致内存溢出
+        UserHolder.clearUserId();
+        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
+    }
+}

+ 20 - 0
novel-cloud-demo/novel-author/src/main/java/com/sf/author/config/WebConfig.java

@@ -0,0 +1,20 @@
+package com.sf.author.config;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
+
+// web相关的配置 需要实现WebMvcConfigurer接口
+@Configuration
+public class WebConfig implements WebMvcConfigurer {
+
+    @Autowired
+    private TokenInterceptor tokenInterceptor;
+
+    @Override
+    public void addInterceptors(InterceptorRegistry registry) {
+//        WebMvcConfigurer.super.addInterceptors(registry);
+        registry.addInterceptor(tokenInterceptor).addPathPatterns("/**");
+    }
+}

+ 65 - 0
novel-cloud-demo/novel-author/src/main/java/com/sf/author/controller/AuthorInfoController.java

@@ -0,0 +1,65 @@
+package com.sf.author.controller;
+
+import com.sf.author.dto.req.AuthorRegisterReqDto;
+import com.sf.author.service.IAuthorInfoService;
+import com.sf.author.util.UserHolder;
+import com.sf.book.client.BookFeign;
+import com.sf.book.client.dto.BookInfoRespDto;
+import com.sf.book.client.dto.BookPageReqDto;
+import com.sf.core.dto.PageRespDto;
+import com.sf.core.dto.RestResp;
+import io.swagger.v3.oas.annotations.Operation;
+import lombok.RequiredArgsConstructor;
+import org.springdoc.core.annotations.ParameterObject;
+import org.springframework.web.bind.annotation.*;
+
+/**
+ * <p>
+ * 作者信息 前端控制器
+ * </p>
+ *
+ * @author baomidou
+ * @since 2024-08-07
+ */
+@RestController
+@RequiredArgsConstructor
+@RequestMapping("/api/author")
+public class AuthorInfoController {
+
+    private final IAuthorInfoService authorInfoService;
+    private final BookFeign bookFeign;
+
+    // http://127.0.0.1:8888/api/author/status
+    @GetMapping("/status")
+    public RestResp<Integer> status() {
+        Long userId = UserHolder.getUserId();
+        System.out.println("userId:" + userId);
+        if (userId == null) {
+            return RestResp.fail("00010", "用户未登录");
+        }
+
+        Integer status = authorInfoService.getStatus(userId);
+        return RestResp.ok(status);
+    }
+
+    // http://127.0.0.1:8888/api/author/register
+    @PostMapping("/register")
+    public RestResp<Void> register(@RequestBody AuthorRegisterReqDto dto) {
+        authorInfoService.register(dto);
+        return RestResp.ok(null);
+    }
+
+    // 作家发表的小说列表
+    // http://127.0.0.1:8888/api/author/books
+    @Operation(summary = "小说发布列表查询接口")
+    @GetMapping("books")
+    public RestResp<PageRespDto<BookInfoRespDto>> listBooks(@ParameterObject BookPageReqDto dto) {
+        Long userId = UserHolder.getUserId();
+        Long authorId = authorInfoService.getAuthorId(userId);
+        dto.setAuthorId(authorId);
+
+        RestResp<PageRespDto<BookInfoRespDto>> restResp = bookFeign.listPublishBooks(dto);
+        return restResp;
+    }
+
+}

+ 59 - 0
novel-cloud-demo/novel-author/src/main/java/com/sf/author/dto/req/AuthorRegisterReqDto.java

@@ -0,0 +1,59 @@
+package com.sf.author.dto.req;
+
+import io.swagger.v3.oas.annotations.media.Schema;
+import jakarta.validation.constraints.*;
+import lombok.Data;
+
+/**
+ * 作家注册 请求DTO
+ *
+ * @author xiongxiaoyang
+ * @date 2022/5/23
+ */
+@Data
+public class AuthorRegisterReqDto {
+
+    // userId可以没有 可以被隐藏
+    @Schema(hidden = true)
+    private Long userId;
+
+    /**
+     * 笔名
+     */
+    @Schema(description = "笔名", required = true)
+    @NotBlank(message = "笔名不能为空!")
+    private String penName;
+
+    /**
+     * 手机号码
+     */
+    @Schema(description = "手机号码", required = true)
+    @NotBlank(message = "手机号不能为空!")
+    @Pattern(regexp = "^1[3|4|5|6|7|8|9][0-9]{9}$", message = "手机号格式不正确!")
+    private String telPhone;
+
+    /**
+     * QQ或微信账号
+     */
+    @Schema(description = "QQ或微信账号", required = true)
+    @NotBlank(message = "QQ或微信账号不能为空!")
+    private String chatAccount;
+
+    /**
+     * 电子邮箱
+     */
+    @Schema(description = "电子邮箱", required = true)
+    @NotBlank(message = "电子邮箱不能为空!")
+    @Email(message = "邮箱格式不正确!")
+    private String email;
+
+    /**
+     * 作品方向;0-男频 1-女频
+     */
+    @Schema(description = "作品方向;0-男频 1-女频", required = true)
+    @NotNull(message = "作品方向不能为空!")
+    @Min(0)
+    @Max(1)
+    private Integer workDirection;
+
+}

+ 83 - 0
novel-cloud-demo/novel-author/src/main/java/com/sf/author/entity/AuthorInfo.java

@@ -0,0 +1,83 @@
+package com.sf.author.entity;
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
+import java.io.Serializable;
+import java.time.LocalDateTime;
+
+import lombok.*;
+
+/**
+ * <p>
+ * 作者信息
+ * </p>
+ *
+ * @author baomidou
+ * @since 2024-08-07
+ */
+@Data
+@Builder
+@NoArgsConstructor
+@AllArgsConstructor
+@TableName("author_info")
+public class AuthorInfo implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    /**
+     * 主键
+     */
+    @TableId(value = "id", type = IdType.AUTO)
+    private Long id;
+
+    /**
+     * 用户ID
+     */
+    private Long userId;
+
+    /**
+     * 邀请码
+     */
+    private String inviteCode;
+
+    /**
+     * 笔名
+     */
+    private String penName;
+
+    /**
+     * 手机号码
+     */
+    private String telPhone;
+
+    /**
+     * QQ或微信账号
+     */
+    private String chatAccount;
+
+    /**
+     * 电子邮箱
+     */
+    private String email;
+
+    /**
+     * 作品方向;0-男频 1-女频
+     */
+    private Integer workDirection;
+
+    /**
+     * 0:正常;1-封禁
+     */
+    private Integer status;
+
+    /**
+     * 创建时间
+     */
+    private LocalDateTime createTime;
+
+    /**
+     * 更新时间
+     */
+    private LocalDateTime updateTime;
+}

+ 16 - 0
novel-cloud-demo/novel-author/src/main/java/com/sf/author/mapper/AuthorInfoMapper.java

@@ -0,0 +1,16 @@
+package com.sf.author.mapper;
+
+import com.sf.author.entity.AuthorInfo;
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+
+/**
+ * <p>
+ * 作者信息 Mapper 接口
+ * </p>
+ *
+ * @author baomidou
+ * @since 2024-08-07
+ */
+public interface AuthorInfoMapper extends BaseMapper<AuthorInfo> {
+
+}

+ 24 - 0
novel-cloud-demo/novel-author/src/main/java/com/sf/author/service/IAuthorInfoService.java

@@ -0,0 +1,24 @@
+package com.sf.author.service;
+
+import com.sf.author.dto.req.AuthorRegisterReqDto;
+import com.sf.author.entity.AuthorInfo;
+import com.baomidou.mybatisplus.extension.service.IService;
+import com.sf.core.dto.RestResp;
+import org.springframework.web.bind.annotation.RequestBody;
+
+/**
+ * <p>
+ * 作者信息 服务类
+ * </p>
+ *
+ * @author baomidou
+ * @since 2024-08-07
+ */
+public interface IAuthorInfoService extends IService<AuthorInfo> {
+
+    Integer getStatus(Long userId);
+
+    Long getAuthorId(Long userId);
+
+    void register(AuthorRegisterReqDto dto);
+}

+ 70 - 0
novel-cloud-demo/novel-author/src/main/java/com/sf/author/service/impl/AuthorInfoServiceImpl.java

@@ -0,0 +1,70 @@
+package com.sf.author.service.impl;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.sf.author.dto.req.AuthorRegisterReqDto;
+import com.sf.author.entity.AuthorInfo;
+import com.sf.author.mapper.AuthorInfoMapper;
+import com.sf.author.service.IAuthorInfoService;
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.sf.author.util.UserHolder;
+import lombok.RequiredArgsConstructor;
+import org.springframework.stereotype.Service;
+
+import java.time.LocalDateTime;
+
+/**
+ * <p>
+ * 作者信息 服务实现类
+ * </p>
+ *
+ * @author baomidou
+ * @since 2024-08-07
+ */
+@Service
+@RequiredArgsConstructor
+public class AuthorInfoServiceImpl extends ServiceImpl<AuthorInfoMapper, AuthorInfo> implements IAuthorInfoService {
+
+    private final AuthorInfoMapper authorInfoMapper;
+
+    @Override
+    public Integer getStatus(Long userId) {
+        LambdaQueryWrapper<AuthorInfo> queryWrapper = new LambdaQueryWrapper<>();
+        queryWrapper.eq(AuthorInfo::getUserId, userId);
+        AuthorInfo authorInfo = authorInfoMapper.selectOne(queryWrapper);
+        if (authorInfo == null) {
+            return null;
+        }
+        return authorInfo.getStatus();
+    }
+
+    @Override
+    public Long getAuthorId(Long userId) {
+        System.out.println("getAuthorId: " + userId);
+        LambdaQueryWrapper<AuthorInfo> queryWrapper = new LambdaQueryWrapper<>();
+        queryWrapper.eq(AuthorInfo::getUserId, userId);
+        AuthorInfo authorInfo = authorInfoMapper.selectOne(queryWrapper);
+        System.out.println("authorInfo: " + authorInfo);
+        if (authorInfo == null) {
+            return null;
+        }
+        return authorInfo.getId();
+    }
+
+    @Override
+    public void register(AuthorRegisterReqDto dto) {
+        // 是在author_info表中增加数据 要和user进行关联
+        AuthorInfo authorInfo = AuthorInfo.builder()
+                .userId(UserHolder.getUserId())
+                .penName(dto.getPenName())
+                .inviteCode("0")
+                .chatAccount(dto.getChatAccount())
+                .email(dto.getEmail())
+                .telPhone(dto.getTelPhone())
+                .workDirection(dto.getWorkDirection())
+                .status(0)
+                .createTime(LocalDateTime.now())
+                .updateTime(LocalDateTime.now())
+                .build();
+        authorInfoMapper.insert(authorInfo);
+    }
+}

+ 37 - 0
novel-cloud-demo/novel-author/src/main/java/com/sf/author/util/JwtUtils.java

@@ -0,0 +1,37 @@
+package com.sf.author.util;
+
+import io.jsonwebtoken.Claims;
+import io.jsonwebtoken.Jws;
+import io.jsonwebtoken.Jwts;
+import io.jsonwebtoken.security.Keys;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+
+// 声明为组件
+@Component
+public class JwtUtils {
+    // @Value 获取配置文件中的值
+    @Value("${novel.jwt.secret}")
+    private String secret;
+
+    public String generateToken(Long uid, String systemKey) {
+        // systemKey是当前系统的标识
+        String token = Jwts.builder()
+                .setHeaderParam("systemKeyHeader", systemKey)
+                .setSubject(uid.toString())
+                .signWith(Keys.hmacShaKeyFor(secret.getBytes())).compact();
+        return token;
+    }
+
+
+    public Long parseToken(String token, String systemKey) {
+        Jws<Claims> claimsJws = Jwts.parserBuilder().setSigningKey(Keys.hmacShaKeyFor(secret.getBytes()))
+                .build().parseClaimsJws(token);
+        // 验证是否是当前系统加密的token
+        if (systemKey.equals(claimsJws.getHeader().get("systemKeyHeader"))) {
+            return Long.parseLong(claimsJws.getBody().getSubject());
+        }
+        return null;
+    }
+
+}

+ 22 - 0
novel-cloud-demo/novel-author/src/main/java/com/sf/author/util/UserHolder.java

@@ -0,0 +1,22 @@
+package com.sf.author.util;
+
+// 用户上下文
+public class UserHolder {
+
+    // 不同的线程存储不同的数据
+    private static final ThreadLocal<Long> userHolder = new ThreadLocal<Long>();
+
+    public static void setUserId(Long userId) {
+        userHolder.set(userId);
+    }
+
+    public static Long getUserId() {
+        // 这里的threadLocal 是一个map结构
+        // map的key 是当前线程 value是当前线程的ThreadLocal
+        return userHolder.get();
+    }
+
+    public static void clearUserId() {
+        userHolder.remove();
+    }
+}

+ 12 - 0
novel-cloud-demo/novel-author/src/main/resources/application.yml

@@ -0,0 +1,12 @@
+spring:
+  #    application:
+  #        name: novel-author
+  profiles:
+    include: common
+
+server:
+  port: 8904
+
+novel:
+  jwt:
+    secret: E66559580A1ADF48CDD928516062F12E

+ 6 - 0
novel-cloud-demo/novel-author/src/main/resources/bootstrap.yml

@@ -0,0 +1,6 @@
+spring:
+  application:
+    name: novel-author
+  # 将通用的application.yml文件引入进来
+  profiles:
+    include: common

+ 5 - 0
novel-cloud-demo/novel-author/src/main/resources/mapper/AuthorInfoMapper.xml

@@ -0,0 +1,5 @@
+<?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.sf.author.mapper.AuthorInfoMapper">
+
+</mapper>

+ 16 - 0
novel-cloud-demo/novel-author/src/test/java/com/sf/author/NovelAuthorApplicationTests.java

@@ -0,0 +1,16 @@
+package com.sf.author;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.boot.test.context.SpringBootTest;
+
+@SpringBootTest
+class NovelAuthorApplicationTests {
+
+	@Test
+	void contextLoads() {
+		int i = 1;
+		byte b1 = (byte) i;
+		int i2 = b1;
+	}
+
+}

+ 4 - 0
novel-cloud-demo/novel-book/novel-book-api/src/main/java/com/sf/book/client/BookFeign.java

@@ -2,6 +2,7 @@ package com.sf.book.client;
 
 import com.sf.book.client.dto.BookCommentRespDto;
 import com.sf.book.client.dto.BookInfoRespDto;
+import com.sf.book.client.dto.BookPageReqDto;
 import com.sf.book.client.fallback.BookFeignFallback;
 import com.sf.core.dto.PageRespDto;
 import com.sf.core.dto.RestResp;
@@ -23,4 +24,7 @@ public interface BookFeign {
     @GetMapping("/api/inner/book/listCommentsByUserId")
     RestResp<PageRespDto<BookCommentRespDto>> listCommentsByUserId(
             @RequestParam("userId") Long userId, @RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize);
+
+    @PostMapping("/api/inner/book/listPublishBooks")
+    RestResp<PageRespDto<BookInfoRespDto>> listPublishBooks(BookPageReqDto dto);
 }

+ 23 - 0
novel-cloud-demo/novel-book/novel-book-api/src/main/java/com/sf/book/client/dto/BookPageReqDto.java

@@ -0,0 +1,23 @@
+package com.sf.book.client.dto;
+
+import com.sf.core.dto.PageReqDto;
+import io.swagger.v3.oas.annotations.media.Schema;
+import lombok.Data;
+
+/**
+ * 章节发布页 请求DTO
+ *
+ * @author xiongxiaoyang
+ * @date 2022/5/23
+ */
+@Data
+public class BookPageReqDto extends PageReqDto {
+
+    /**
+     * 作家ID
+     */
+    @Schema(description = "作家ID", required = true)
+    private Long authorId;
+
+
+}

+ 6 - 0
novel-cloud-demo/novel-book/novel-book-api/src/main/java/com/sf/book/client/fallback/BookFeignFallback.java

@@ -3,6 +3,7 @@ package com.sf.book.client.fallback;
 import com.sf.book.client.BookFeign;
 import com.sf.book.client.dto.BookCommentRespDto;
 import com.sf.book.client.dto.BookInfoRespDto;
+import com.sf.book.client.dto.BookPageReqDto;
 import com.sf.core.dto.PageRespDto;
 import com.sf.core.dto.RestResp;
 import org.springframework.stereotype.Component;
@@ -23,4 +24,9 @@ public class BookFeignFallback implements BookFeign {
     public RestResp<PageRespDto<BookCommentRespDto>> listCommentsByUserId(Long userId, Integer pageNum, Integer pageSize) {
         return RestResp.ok(PageRespDto.of(0, 0, 0, null));
     }
+
+    @Override
+    public RestResp<PageRespDto<BookInfoRespDto>> listPublishBooks(BookPageReqDto dto) {
+        return null;
+    }
 }

+ 23 - 4
novel-cloud-demo/novel-book/novel-book-service/src/main/java/com/sf/book/controller/BookChapterController.java

@@ -8,11 +8,8 @@ import io.swagger.v3.oas.annotations.Operation;
 import io.swagger.v3.oas.annotations.Parameter;
 import io.swagger.v3.oas.annotations.tags.Tag;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.*;
 import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestParam;
-import org.springframework.web.bind.annotation.RestController;
 
 import java.util.List;
 
@@ -52,4 +49,26 @@ public class BookChapterController {
         return RestResp.ok(chapterAboutRespDto);
     }
 
+    /**
+     * 获取上一章节ID接口
+     */
+    @Operation(summary = "获取上一章节ID接口")
+    @GetMapping("/api/front/book/pre_chapter_id/{chapterId}")
+    public RestResp<Long> getPreChapterId(
+            @Parameter(description = "章节ID") @PathVariable("chapterId") Long chapterId) {
+        Long preChapterId = bookChapterService.getPreChapterId(chapterId);
+        return RestResp.ok(preChapterId);
+    }
+
+    /**
+     * 获取下一章节ID接口
+     */
+    @Operation(summary = "获取下一章节ID接口")
+    @GetMapping("/api/front/book/next_chapter_id/{chapterId}")
+    public RestResp<Long> getNextChapterId(
+            @Parameter(description = "章节ID") @PathVariable("chapterId") Long chapterId) {
+        Long nextChapterId = bookChapterService.getNextChapterId(chapterId);
+        return RestResp.ok(nextChapterId);
+    }
+
 }

+ 13 - 0
novel-cloud-demo/novel-book/novel-book-service/src/main/java/com/sf/book/controller/inner/InnerBookController.java

@@ -1,7 +1,9 @@
 package com.sf.book.controller.inner;
 
+import com.sf.book.dto.inner.BookPageReqDto;
 import com.sf.book.dto.inner.InnerBookCommentRespDto;
 import com.sf.book.dto.resp.BookInfoRespDto;
+import com.sf.book.service.IAuthorBookService;
 import com.sf.book.service.IInnerBookService;
 import com.sf.core.dto.PageRespDto;
 import com.sf.core.dto.RestResp;
@@ -16,6 +18,7 @@ import java.util.List;
 public class InnerBookController {
 
     private final IInnerBookService innerBookService;
+    private final IAuthorBookService authorBookService;
 
     // 因为要接收的参数是list 在openfeign的调用逻辑中 不能使用@RequestParam 要使用@RequestBody
     // 这里也不能是get请求  为了结合@RequestBody  要使用post请求
@@ -34,4 +37,14 @@ public class InnerBookController {
         System.out.println(commentList);
         return RestResp.ok(commentList);
     }
+
+    // 根据作者id找到书籍信息
+    @PostMapping("/api/inner/book/listPublishBooks")
+    public RestResp<PageRespDto<BookInfoRespDto>> listPublishBooks(@RequestBody BookPageReqDto dto){
+        System.out.println("listPublishBooks:" + dto);
+        PageRespDto<BookInfoRespDto> dtoPageRespDto = authorBookService.listPublishBooks(dto);
+        System.out.println("listPublishBooks:" + dtoPageRespDto);
+        return RestResp.ok(dtoPageRespDto);
+    }
+
 }

+ 23 - 0
novel-cloud-demo/novel-book/novel-book-service/src/main/java/com/sf/book/dto/inner/BookPageReqDto.java

@@ -0,0 +1,23 @@
+package com.sf.book.dto.inner;
+
+import com.sf.core.dto.PageReqDto;
+import io.swagger.v3.oas.annotations.media.Schema;
+import lombok.Data;
+
+/**
+ * 章节发布页 请求DTO
+ *
+ * @author xiongxiaoyang
+ * @date 2022/5/23
+ */
+@Data
+public class BookPageReqDto extends PageReqDto {
+
+    /**
+     * 作家ID
+     */
+    @Schema(description = "作家ID", required = true)
+    private Long authorId;
+
+
+}

+ 12 - 0
novel-cloud-demo/novel-book/novel-book-service/src/main/java/com/sf/book/service/IAuthorBookService.java

@@ -0,0 +1,12 @@
+package com.sf.book.service;
+
+import com.sf.book.dto.inner.BookPageReqDto;
+import com.sf.book.dto.resp.BookInfoRespDto;
+import com.sf.core.dto.PageRespDto;
+import org.springframework.web.bind.annotation.RequestBody;
+
+public interface IAuthorBookService {
+
+    PageRespDto<BookInfoRespDto> listPublishBooks(BookPageReqDto dto);
+
+}

+ 16 - 0
novel-cloud-demo/novel-book/novel-book-service/src/main/java/com/sf/book/service/IBookChapterService.java

@@ -20,4 +20,20 @@ public interface IBookChapterService extends IService<BookChapter> {
     List<BookChapterRespDto> getBookChapterByBookId(Long bookId);
 
     BookChapterAboutRespDto lastChapterAbout(Long bookId);
+
+    /**
+     * 获取上一章节ID
+     *
+     * @param chapterId 章节ID
+     * @return 上一章节ID
+     */
+    Long getPreChapterId(Long chapterId);
+
+    /**
+     * 获取下一章节ID
+     *
+     * @param chapterId 章节ID
+     * @return 下一章节ID
+     */
+    Long getNextChapterId(Long chapterId);
 }

+ 49 - 0
novel-cloud-demo/novel-book/novel-book-service/src/main/java/com/sf/book/service/impl/AuthorBookServiceImpl.java

@@ -0,0 +1,49 @@
+package com.sf.book.service.impl;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.baomidou.mybatisplus.core.metadata.IPage;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.sf.book.dto.inner.BookPageReqDto;
+import com.sf.book.dto.resp.BookInfoRespDto;
+import com.sf.book.entity.BookInfo;
+import com.sf.book.mapper.BookInfoMapper;
+import com.sf.book.service.IAuthorBookService;
+import com.sf.core.dto.PageRespDto;
+import com.sf.core.dto.RestResp;
+import lombok.RequiredArgsConstructor;
+import org.springframework.stereotype.Service;
+
+import java.util.List;
+
+@Service
+@RequiredArgsConstructor
+public class AuthorBookServiceImpl implements IAuthorBookService {
+
+    private final BookInfoMapper bookInfoMapper;
+
+    @Override
+    public PageRespDto<BookInfoRespDto> listPublishBooks(BookPageReqDto dto) {
+        IPage<BookInfo> page = new Page<>();
+        page.setCurrent(dto.getPageNum());
+        page.setSize(dto.getPageSize());
+        LambdaQueryWrapper<BookInfo> queryWrapper = new LambdaQueryWrapper<>();
+        queryWrapper.eq(BookInfo::getAuthorId, dto.getAuthorId())
+                .orderByDesc(BookInfo::getCreateTime);
+        IPage<BookInfo> bookInfoPage = bookInfoMapper.selectPage(page, queryWrapper);
+        List<BookInfo> records = bookInfoPage.getRecords();
+        List<BookInfoRespDto> bookInfoRespDtos =
+                records.stream().map(bookInfo -> BookInfoRespDto.builder()
+                        .id(bookInfo.getId())
+                        .bookName(bookInfo.getBookName())
+                        .picUrl(bookInfo.getPicUrl())
+                        .categoryName(bookInfo.getCategoryName())
+                        .wordCount(bookInfo.getWordCount())
+                        .visitCount(bookInfo.getVisitCount())
+                        .updateTime(bookInfo.getUpdateTime())
+                        .build()).toList();
+        PageRespDto<BookInfoRespDto> pageRespDto = PageRespDto.of(dto.getPageNum(), dto.getPageSize(), page.getTotal(), bookInfoRespDtos);
+        return pageRespDto;
+
+    }
+}

+ 44 - 0
novel-cloud-demo/novel-book/novel-book-service/src/main/java/com/sf/book/service/impl/BookChapterServiceImpl.java

@@ -1,6 +1,7 @@
 package com.sf.book.service.impl;
 
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.sf.book.dto.resp.BookChapterAboutRespDto;
 import com.sf.book.dto.resp.BookChapterRespDto;
 import com.sf.book.entity.BookChapter;
@@ -15,6 +16,7 @@ import org.springframework.stereotype.Service;
 
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Optional;
 
 /**
  * <p>
@@ -100,4 +102,46 @@ public class BookChapterServiceImpl extends ServiceImpl<BookChapterMapper, BookC
 
         return chapterAboutRespDto;
     }
+
+
+    @Override
+    public Long getPreChapterId(Long chapterId) {
+        // 查询小说ID 和 章节号
+        BookChapter bookChapter = bookChapterMapper.selectById(chapterId);
+        Long bookId = bookChapter.getBookId();
+        Integer chapterNum = bookChapter.getChapterNum();
+
+        // 查询上一章信息并返回章节ID
+        LambdaQueryWrapper<BookChapter> queryWrapper = new LambdaQueryWrapper<>();
+        queryWrapper.eq(BookChapter::getBookId, bookId)
+                .lt(BookChapter::getChapterNum, chapterNum)
+                .orderByDesc(BookChapter::getChapterNum)
+                .last("limit 1");
+        BookChapter preBookChapter = bookChapterMapper.selectOne(queryWrapper);
+        if (preBookChapter == null) {
+            return null;
+        }
+        return preBookChapter.getId();
+    }
+
+    @Override
+    public Long getNextChapterId(Long chapterId) {
+        // 查询小说ID 和 章节号
+        BookChapter bookChapter = bookChapterMapper.selectById(chapterId);
+        Long bookId = bookChapter.getBookId();
+        Integer chapterNum = bookChapter.getChapterNum();
+
+        // 查询下一章信息并返回章节ID
+        LambdaQueryWrapper<BookChapter> queryWrapper = new LambdaQueryWrapper<>();
+        queryWrapper.eq(BookChapter::getBookId, bookId)
+                .gt(BookChapter::getChapterNum, chapterNum)
+                .orderByAsc(BookChapter::getChapterNum)
+                .last("limit 1");
+        BookChapter nextBookChapter = bookChapterMapper.selectOne(queryWrapper);
+        if (nextBookChapter == null) {
+            return null;
+        }
+        return nextBookChapter.getId();
+    }
+
 }

+ 10 - 18
novel-cloud-demo/novel-core/src/main/java/com/sf/core/util/GeneUtils.java

@@ -43,36 +43,28 @@ public class GeneUtils {
 //                list.add("book_chapter"); // 书籍章节表
 //                list.add("book_content"); // 章节内容表
 //                list.add("book_category"); // 书籍种类表
-                list.add("book_comment"); // 书籍评论表
+//                list.add("book_comment"); // 书籍评论表
                 break;
             case "news":
                 projectPathTmp = "novel-news/";
                 packageNameTmp = ".news";
 
-                list.add("news_info"); // 新闻列表
-                list.add("news_content"); // 新闻内容表
+//                list.add("news_info"); // 新闻列表
+//                list.add("news_content"); // 新闻内容表
                 break;
             case "user":
                 projectPathTmp = "novel-user/novel-user-service/";
                 packageNameTmp = ".user";
 
-                list.add("user_info"); // 用户信息表
+//                list.add("user_info"); // 用户信息表
+                break;
+            case "author":
+                projectPathTmp = "novel-author/";
+                packageNameTmp = ".author";
+
+                list.add("author_info");  // 作者信息表
             default:
         }
-//        list.add("home_book");  // 首页书籍信息表
-//        list.add("home_friend_link"); // 首页友情链接表
-
-//        list.add("book_info");  // 书籍表
-//        list.add("book_chapter"); // 书籍章节表
-//        list.add("book_content"); // 章节内容表
-//        list.add("book_category"); // 书籍种类表
-
-//        list.add("news_info"); // 新闻列表
-//        list.add("news_content"); // 新闻内容表
-
-//        list.add("user_info"); // 用户信息表
-//        list.add("book_comment"); // 书籍评论表
-//        list.add("author_info"); // 作者信息表
 
         // 因为下列的代码是lambda 所以此处做一个中转
         String projectPath = projectPathTmp;

+ 6 - 0
novel-cloud-demo/novel-gateway/src/main/resources/application.yml

@@ -45,3 +45,9 @@ spring:
           predicates:
             # 路由断言,路径相匹配的进行路由
             - Path=/api/front/user/**,/api/front/resource/**
+        - id: novel-author
+          # 使用loadbalancer负载均衡来分发
+          uri: lb://novel-author
+          predicates:
+            # 路由断言,路径相匹配的进行路由
+            - Path=/api/author/**

+ 3 - 2
novel-cloud-demo/pom.xml

@@ -20,6 +20,7 @@
         <module>novel-gateway</module>
         <module>novel-news</module>
         <module>novel-user</module>
+        <module>novel-author</module>
     </modules>
 
     <!-- 使用属性配置来管理依赖版本 -->
@@ -157,13 +158,13 @@
                 <groupId>io.jsonwebtoken</groupId>
                 <artifactId>jjwt-impl</artifactId>
                 <version>${jjwt.version}</version>
-<!--                <scope>runtime</scope>-->
+                <!--                <scope>runtime</scope>-->
             </dependency>
             <dependency>
                 <groupId>io.jsonwebtoken</groupId>
                 <artifactId>jjwt-jackson</artifactId>
                 <version>${jjwt.version}</version>
-<!--                <scope>runtime</scope>-->
+                <!--                <scope>runtime</scope>-->
             </dependency>
 
         </dependencies>