diff --git a/version5/.idea/.gitignore b/.idea/.gitignore similarity index 100% rename from version5/.idea/.gitignore rename to .idea/.gitignore diff --git a/.idea/RPC-Java-F.iml b/.idea/RPC-Java-F.iml new file mode 100644 index 0000000..d6ebd48 --- /dev/null +++ b/.idea/RPC-Java-F.iml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100644 index 0000000..12548f5 --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/encodings.xml b/.idea/encodings.xml new file mode 100644 index 0000000..0cc3557 --- /dev/null +++ b/.idea/encodings.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/jarRepositories.xml b/.idea/jarRepositories.xml new file mode 100644 index 0000000..6f31448 --- /dev/null +++ b/.idea/jarRepositories.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..cfdc549 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..89ab409 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/consumer/.gitattributes b/consumer/.gitattributes new file mode 100644 index 0000000..3b41682 --- /dev/null +++ b/consumer/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/consumer/.gitignore b/consumer/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/consumer/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/consumer/.mvn/wrapper/maven-wrapper.properties b/consumer/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..d58dfb7 --- /dev/null +++ b/consumer/.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 +# +# http://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.9/apache-maven-3.9.9-bin.zip diff --git a/consumer/mvnw b/consumer/mvnw new file mode 100644 index 0000000..19529dd --- /dev/null +++ b/consumer/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 +# +# http://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-,maven-mvnd--}/ +[ -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 "$@" diff --git a/consumer/mvnw.cmd b/consumer/mvnw.cmd new file mode 100644 index 0000000..249bdf3 --- /dev/null +++ b/consumer/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 http://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-,maven-mvnd--}/ +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" diff --git a/consumer/pom.xml b/consumer/pom.xml new file mode 100644 index 0000000..47ad3d7 --- /dev/null +++ b/consumer/pom.xml @@ -0,0 +1,95 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.0.0.RELEASE + + + com.example + consumer + 0.0.1-SNAPSHOT + consumer + consumer + + + + + + + + + + + + + + + 8 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.example + publicInterface + 1.0-SNAPSHOT + + + + org.example + version4 + 1.0-SNAPSHOT + compile + + + org.springframework.boot + spring-boot-starter-actuator + + + org.projectlombok + lombok + provided + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + 8 + 8 + + + + + + diff --git a/consumer/src/main/java/com/example/consumer/ConsumerApplication.java b/consumer/src/main/java/com/example/consumer/ConsumerApplication.java new file mode 100644 index 0000000..b4a0459 --- /dev/null +++ b/consumer/src/main/java/com/example/consumer/ConsumerApplication.java @@ -0,0 +1,17 @@ +package com.example.consumer; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; +import part1.Server.integration.EnableConsumer; + +@SpringBootApplication +@EnableConsumer +//@ComponentScan(basePackages = {"com.example.consumer.web.controller"}) +public class ConsumerApplication { + + public static void main(String[] args) { + SpringApplication.run(ConsumerApplication.class, args); + } + +} diff --git a/consumer/src/main/java/com/example/consumer/web/controller/testController.java b/consumer/src/main/java/com/example/consumer/web/controller/testController.java new file mode 100644 index 0000000..d64e1c0 --- /dev/null +++ b/consumer/src/main/java/com/example/consumer/web/controller/testController.java @@ -0,0 +1,44 @@ +package com.example.consumer.web.controller; + +import com.publicInterface.dto.User; +import com.publicInterface.service.UserService; +import lombok.extern.slf4j.Slf4j; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import part1.Server.integration.References; + +/** + * @Author: yty + * @Description: TODO + * @DateTime: 2024/11/08 15:53 + **/ +@RestController +@RequestMapping("/api/consumer/test") +public class testController { + + Logger log = LoggerFactory.getLogger(testController.class); + + @References(version = "1.2") + private UserService userService2; + + @References(version = "1.1") + private UserService userService1; + + @GetMapping(value = "/test1") + public User page1() { + User user = userService1.getUserByUserId(1); + log.info(user.toString()); + return user; + } + + @GetMapping(value = "/test2") + public User page2() { + User user = userService2.getUserByUserId(2); + log.info(user.toString()); + return user; + } +} diff --git a/consumer/src/main/resources/application.properties b/consumer/src/main/resources/application.properties new file mode 100644 index 0000000..d11eead --- /dev/null +++ b/consumer/src/main/resources/application.properties @@ -0,0 +1,3 @@ +spring.application.name=consumer +server.port=9091 +spring.web.resources.static-locations=[] diff --git a/provider/.gitattributes b/provider/.gitattributes new file mode 100644 index 0000000..3b41682 --- /dev/null +++ b/provider/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/provider/.gitignore b/provider/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/provider/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/provider/.mvn/wrapper/maven-wrapper.properties b/provider/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..d58dfb7 --- /dev/null +++ b/provider/.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 +# +# http://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.9/apache-maven-3.9.9-bin.zip diff --git a/provider/mvnw b/provider/mvnw new file mode 100644 index 0000000..19529dd --- /dev/null +++ b/provider/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 +# +# http://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-,maven-mvnd--}/ +[ -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 "$@" diff --git a/provider/mvnw.cmd b/provider/mvnw.cmd new file mode 100644 index 0000000..249bdf3 --- /dev/null +++ b/provider/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 http://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-,maven-mvnd--}/ +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" diff --git a/provider/pom.xml b/provider/pom.xml new file mode 100644 index 0000000..2c7ba04 --- /dev/null +++ b/provider/pom.xml @@ -0,0 +1,74 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.0.0.RELEASE + + + com.example + provider + 0.0.1-SNAPSHOT + provider + provider + + + + + + + + + + + + + + + 8 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + org.example + publicInterface + 1.0-SNAPSHOT + compile + + + org.example + version4 + 1.0-SNAPSHOT + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + 8 + 8 + + + + + + diff --git a/provider/src/main/java/com/example/provider/ProviderApplication.java b/provider/src/main/java/com/example/provider/ProviderApplication.java new file mode 100644 index 0000000..c2d5a69 --- /dev/null +++ b/provider/src/main/java/com/example/provider/ProviderApplication.java @@ -0,0 +1,15 @@ +package com.example.provider; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import part1.Server.integration.EnableProvider; + +@SpringBootApplication +@EnableProvider +public class ProviderApplication { + + public static void main(String[] args) { + SpringApplication.run(ProviderApplication.class, args); + } + +} diff --git a/provider/src/main/java/com/example/provider/web/service/impl/UserServiceImpl1.java b/provider/src/main/java/com/example/provider/web/service/impl/UserServiceImpl1.java new file mode 100644 index 0000000..74a7c87 --- /dev/null +++ b/provider/src/main/java/com/example/provider/web/service/impl/UserServiceImpl1.java @@ -0,0 +1,31 @@ +package com.example.provider.web.service.impl; + +import com.publicInterface.service.UserService; +import com.publicInterface.dto.User; +import part1.Server.integration.RpcService; +import java.util.Random; +import java.util.UUID; + +/** + * @Author: yty + * @Description: TODO + * @DateTime: 2024/11/08 15:05 + **/ +@RpcService(version = "1.1") +public class UserServiceImpl1 implements UserService { + @Override + public User getUserByUserId(Integer id) { + System.out.println("实现方法1.1:客户端查询了"+id+"的用户"); + // 模拟从数据库中取用户的行为 + Random random = new Random(); + return User.builder().userName(UUID.randomUUID().toString()) + .id(id) + .sex(random.nextBoolean()).build(); + } + + @Override + public Integer insertUserId(User user) { + System.out.println("实现方法1.1:插入数据成功"+user.getUserName()); + return user.getId(); + } +} \ No newline at end of file diff --git a/provider/src/main/java/com/example/provider/web/service/impl/UserServiceImpl2.java b/provider/src/main/java/com/example/provider/web/service/impl/UserServiceImpl2.java new file mode 100644 index 0000000..4fcbdb0 --- /dev/null +++ b/provider/src/main/java/com/example/provider/web/service/impl/UserServiceImpl2.java @@ -0,0 +1,32 @@ +package com.example.provider.web.service.impl; + +import com.publicInterface.dto.User; +import com.publicInterface.service.UserService; +import part1.Server.integration.RpcService; + +import java.util.Random; +import java.util.UUID; + +/** + * @Author: yty + * @Description: TODO + * @DateTime: 2024/11/08 15:05 + **/ +@RpcService(version = "1.2") +public class UserServiceImpl2 implements UserService { + @Override + public User getUserByUserId(Integer id) { + System.out.println("实现方法1.2:客户端查询了"+id+"的用户"); + // 模拟从数据库中取用户的行为 + Random random = new Random(); + return User.builder().userName(UUID.randomUUID().toString()) + .id(id) + .sex(random.nextBoolean()).build(); + } + + @Override + public Integer insertUserId(User user) { + System.out.println("实现方法1.2:插入数据成功"+user.getUserName()); + return user.getId(); + } +} \ No newline at end of file diff --git a/provider/src/main/resources/application.properties b/provider/src/main/resources/application.properties new file mode 100644 index 0000000..1b4fe40 --- /dev/null +++ b/provider/src/main/resources/application.properties @@ -0,0 +1,3 @@ +spring.application.name=provider +server.port=9090 + diff --git a/version1/pom.xml b/publicInterface/pom.xml similarity index 50% rename from version1/pom.xml rename to publicInterface/pom.xml index 0761b8b..e443676 100644 --- a/version1/pom.xml +++ b/publicInterface/pom.xml @@ -5,8 +5,9 @@ 4.0.0 org.example - version1 + publicInterface 1.0-SNAPSHOT + 8 8 @@ -14,36 +15,29 @@ - org.projectlombok - lombok - 1.18.30 + org.example + version4 + 1.0-SNAPSHOT compile - org.slf4j - slf4j-log4j12 - 1.7.25 - - - org.apache.logging.log4j - log4j-1.2-api - 2.8.2 - - - - io.netty - netty-all - 4.1.51.Final + org.projectlombok + lombok + 1.18.34 compile - - - org.apache.curator - curator-recipes - 5.1.0 - - - - + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + 8 + 8 + + + + \ No newline at end of file diff --git a/version1/src/main/java/part3/common/pojo/User.java b/publicInterface/src/main/java/com/publicInterface/dto/User.java similarity index 90% rename from version1/src/main/java/part3/common/pojo/User.java rename to publicInterface/src/main/java/com/publicInterface/dto/User.java index 46a0a87..09bf50a 100644 --- a/version1/src/main/java/part3/common/pojo/User.java +++ b/publicInterface/src/main/java/com/publicInterface/dto/User.java @@ -1,4 +1,5 @@ -package part3.common.pojo; +package com.publicInterface.dto; + import lombok.AllArgsConstructor; import lombok.Builder; @@ -8,7 +9,6 @@ import java.io.Serializable; /** - * @author wxx * @version 1.0 * @create 2024/1/28 17:50 */ diff --git a/version1/src/main/java/part2/common/service/UserService.java b/publicInterface/src/main/java/com/publicInterface/service/UserService.java similarity index 76% rename from version1/src/main/java/part2/common/service/UserService.java rename to publicInterface/src/main/java/com/publicInterface/service/UserService.java index b6817fe..cce6637 100644 --- a/version1/src/main/java/part2/common/service/UserService.java +++ b/publicInterface/src/main/java/com/publicInterface/service/UserService.java @@ -1,10 +1,9 @@ -package part2.common.service; +package com.publicInterface.service; -import part2.common.pojo.User; +import com.publicInterface.dto.User; /** - * @author wxx * @version 1.0 * @create 2024/1/28 16:27 */ diff --git a/publicInterface/target/classes/com/publicInterface/dto/User$UserBuilder.class b/publicInterface/target/classes/com/publicInterface/dto/User$UserBuilder.class new file mode 100644 index 0000000..dfbd4a0 Binary files /dev/null and b/publicInterface/target/classes/com/publicInterface/dto/User$UserBuilder.class differ diff --git a/publicInterface/target/classes/com/publicInterface/dto/User.class b/publicInterface/target/classes/com/publicInterface/dto/User.class new file mode 100644 index 0000000..756bf33 Binary files /dev/null and b/publicInterface/target/classes/com/publicInterface/dto/User.class differ diff --git a/publicInterface/target/classes/com/publicInterface/service/UserService.class b/publicInterface/target/classes/com/publicInterface/service/UserService.class new file mode 100644 index 0000000..939c55e Binary files /dev/null and b/publicInterface/target/classes/com/publicInterface/service/UserService.class differ diff --git a/publicInterface/target/maven-archiver/pom.properties b/publicInterface/target/maven-archiver/pom.properties new file mode 100644 index 0000000..e91d27c --- /dev/null +++ b/publicInterface/target/maven-archiver/pom.properties @@ -0,0 +1,5 @@ +#Generated by Maven +#Tue Dec 10 10:12:20 CST 2024 +version=1.0-SNAPSHOT +groupId=org.example +artifactId=publicInterface diff --git a/publicInterface/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst b/publicInterface/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst new file mode 100644 index 0000000..f272055 --- /dev/null +++ b/publicInterface/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst @@ -0,0 +1,3 @@ +com\publicInterface\dto\User$UserBuilder.class +com\publicInterface\service\UserService.class +com\publicInterface\dto\User.class diff --git a/publicInterface/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst b/publicInterface/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst new file mode 100644 index 0000000..97d2b08 --- /dev/null +++ b/publicInterface/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst @@ -0,0 +1,2 @@ +D:\developSoftware\backDev\Code\DEV-RPC-Java\publicInterface\src\main\java\com\publicInterface\service\UserService.java +D:\developSoftware\backDev\Code\DEV-RPC-Java\publicInterface\src\main\java\com\publicInterface\dto\User.java diff --git a/publicInterface/target/publicInterface-1.0-SNAPSHOT.jar b/publicInterface/target/publicInterface-1.0-SNAPSHOT.jar new file mode 100644 index 0000000..b614b97 Binary files /dev/null and b/publicInterface/target/publicInterface-1.0-SNAPSHOT.jar differ diff --git a/version1/src/main/java/part1/Client/IOClient.java b/version1/src/main/java/part1/Client/IOClient.java deleted file mode 100644 index 8c7f61f..0000000 --- a/version1/src/main/java/part1/Client/IOClient.java +++ /dev/null @@ -1,36 +0,0 @@ -package part1.Client; - - - -import part1.common.Message.RpcRequest; -import part1.common.Message.RpcResponse; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.net.Socket; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/4 18:31 - */ -public class IOClient { - //这里负责底层与服务端的通信,发送request,返回response - public static RpcResponse sendRequest(String host, int port, RpcRequest request){ - try { - Socket socket=new Socket(host, port); - ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream()); - ObjectInputStream ois=new ObjectInputStream(socket.getInputStream()); - - oos.writeObject(request); - oos.flush(); - - RpcResponse response=(RpcResponse) ois.readObject(); - return response; - } catch (IOException | ClassNotFoundException e) { - e.printStackTrace(); - return null; - } - } -} diff --git a/version1/src/main/java/part1/Client/TestClient.java b/version1/src/main/java/part1/Client/TestClient.java deleted file mode 100644 index f9b7bab..0000000 --- a/version1/src/main/java/part1/Client/TestClient.java +++ /dev/null @@ -1,25 +0,0 @@ -package part1.Client; - - -import part1.Client.proxy.ClientProxy; -import part1.common.service.UserService; -import part1.common.pojo.User; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/6 18:39 - */ -public class TestClient { - public static void main(String[] args) { - ClientProxy clientProxy=new ClientProxy("127.0.0.1",9999); - UserService proxy=clientProxy.getProxy(UserService.class); - - User user = proxy.getUserByUserId(1); - System.out.println("从服务端得到的user="+user.toString()); - - User u=User.builder().id(100).userName("wxx").sex(true).build(); - Integer id = proxy.insertUserId(u); - System.out.println("向服务端插入user的id"+id); - } -} diff --git a/version1/src/main/java/part1/Client/proxy/ClientProxy.java b/version1/src/main/java/part1/Client/proxy/ClientProxy.java deleted file mode 100644 index 3701bdf..0000000 --- a/version1/src/main/java/part1/Client/proxy/ClientProxy.java +++ /dev/null @@ -1,40 +0,0 @@ -package part1.Client.proxy; - - -import lombok.AllArgsConstructor; -import part1.Client.IOClient; -import part1.common.Message.RpcRequest; -import part1.common.Message.RpcResponse; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/6 16:49 - */ -@AllArgsConstructor -public class ClientProxy implements InvocationHandler { - //传入参数service接口的class对象,反射封装成一个request - private String host; - private int port; - - //jdk动态代理,每一次代理对象调用方法,都会经过此方法增强(反射获取request对象,socket发送到服务端) - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - //构建request - RpcRequest request=RpcRequest.builder() - .interfaceName(method.getDeclaringClass().getName()) - .methodName(method.getName()) - .params(args).paramsType(method.getParameterTypes()).build(); - //IOClient.sendRequest 和服务端进行数据传输 - RpcResponse response= IOClient.sendRequest(host,port,request); - return response.getData(); - } - public T getProxy(Class clazz){ - Object o = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, this); - return (T)o; - } -} diff --git a/version1/src/main/java/part1/Server/TestServer.java b/version1/src/main/java/part1/Server/TestServer.java deleted file mode 100644 index 682b912..0000000 --- a/version1/src/main/java/part1/Server/TestServer.java +++ /dev/null @@ -1,25 +0,0 @@ -package part1.Server; - - -import part1.Server.server.RpcServer; -import part1.common.service.Impl.UserServiceImpl; -import part1.common.service.UserService; -import part1.Server.server.impl.SimpleRPCRPCServer; -import part1.Server.provider.ServiceProvider; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/11 19:39 - */ -public class TestServer { - public static void main(String[] args) { - UserService userService=new UserServiceImpl(); - - ServiceProvider serviceProvider=new ServiceProvider(); - serviceProvider.provideServiceInterface(userService); - - RpcServer rpcServer=new SimpleRPCRPCServer(serviceProvider); - rpcServer.start(9999); - } -} diff --git a/version1/src/main/java/part1/Server/provider/ServiceProvider.java b/version1/src/main/java/part1/Server/provider/ServiceProvider.java deleted file mode 100644 index 8864448..0000000 --- a/version1/src/main/java/part1/Server/provider/ServiceProvider.java +++ /dev/null @@ -1,34 +0,0 @@ -package part1.Server.provider; - -import java.util.HashMap; -import java.util.Map; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/16 17:35 - */ -//本地服务存放器 -public class ServiceProvider { - //集合中存放服务的实例 - private Map interfaceProvider; - - public ServiceProvider(){ - this.interfaceProvider=new HashMap<>(); - } - //本地注册服务 - - public void provideServiceInterface(Object service){ - String serviceName=service.getClass().getName(); - Class[] interfaceName=service.getClass().getInterfaces(); - - for (Class clazz:interfaceName){ - interfaceProvider.put(clazz.getName(),service); - } - - } - //获取服务实例 - public Object getService(String interfaceName){ - return interfaceProvider.get(interfaceName); - } -} diff --git a/version1/src/main/java/part1/Server/server/RpcServer.java b/version1/src/main/java/part1/Server/server/RpcServer.java deleted file mode 100644 index 76df981..0000000 --- a/version1/src/main/java/part1/Server/server/RpcServer.java +++ /dev/null @@ -1,12 +0,0 @@ -package part1.Server.server; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/12 11:26 - */ -public interface RpcServer { - //开启监听 - void start(int port); - void stop(); -} diff --git a/version1/src/main/java/part1/Server/server/impl/SimpleRPCRPCServer.java b/version1/src/main/java/part1/Server/server/impl/SimpleRPCRPCServer.java deleted file mode 100644 index 09afdff..0000000 --- a/version1/src/main/java/part1/Server/server/impl/SimpleRPCRPCServer.java +++ /dev/null @@ -1,40 +0,0 @@ -package part1.Server.server.impl; - - -import lombok.AllArgsConstructor; -import part1.Server.server.RpcServer; -import part1.Server.server.work.WorkThread; -import part1.Server.provider.ServiceProvider; - -import java.io.IOException; -import java.net.ServerSocket; -import java.net.Socket; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/12 11:37 - */ -@AllArgsConstructor -public class SimpleRPCRPCServer implements RpcServer { - private ServiceProvider serviceProvide; - @Override - public void start(int port) { - try { - ServerSocket serverSocket=new ServerSocket(port); - System.out.println("服务器启动了"); - while (true) { - //如果没有连接,会堵塞在这里 - Socket socket = serverSocket.accept(); - //有连接,创建一个新的线程执行处理 - new Thread(new WorkThread(socket,serviceProvide)).start(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Override - public void stop() { - } -} diff --git a/version1/src/main/java/part1/Server/server/impl/ThreadPoolRPCRPCServer.java b/version1/src/main/java/part1/Server/server/impl/ThreadPoolRPCRPCServer.java deleted file mode 100644 index 0d32e1f..0000000 --- a/version1/src/main/java/part1/Server/server/impl/ThreadPoolRPCRPCServer.java +++ /dev/null @@ -1,58 +0,0 @@ -package part1.Server.server.impl; - - -import part1.Server.server.RpcServer; -import part1.Server.server.work.WorkThread; -import part1.Server.provider.ServiceProvider; - -import java.io.IOException; -import java.net.ServerSocket; -import java.net.Socket; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/19 15:30 - */ -public class ThreadPoolRPCRPCServer implements RpcServer { - private final ThreadPoolExecutor threadPool; - private ServiceProvider serviceProvider; - - public ThreadPoolRPCRPCServer(ServiceProvider serviceProvider){ - threadPool=new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), - 1000,60, TimeUnit.SECONDS,new ArrayBlockingQueue<>(100)); - this.serviceProvider= serviceProvider; - } - public ThreadPoolRPCRPCServer(ServiceProvider serviceProvider, int corePoolSize, - int maximumPoolSize, - long keepAliveTime, - TimeUnit unit, - BlockingQueue workQueue){ - - threadPool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue); - this.serviceProvider = serviceProvider; - } - - @Override - public void start(int port) { - System.out.println("服务端启动了"); - try { - ServerSocket serverSocket=new ServerSocket(); - while (true){ - Socket socket= serverSocket.accept(); - threadPool.execute(new WorkThread(socket,serviceProvider)); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Override - public void stop() { - - } -} diff --git a/version1/src/main/java/part1/Server/server/work/WorkThread.java b/version1/src/main/java/part1/Server/server/work/WorkThread.java deleted file mode 100644 index 064b9c2..0000000 --- a/version1/src/main/java/part1/Server/server/work/WorkThread.java +++ /dev/null @@ -1,58 +0,0 @@ -package part1.Server.server.work; - - -import lombok.AllArgsConstructor; -import part1.Server.provider.ServiceProvider; -import part1.common.Message.RpcRequest; -import part1.common.Message.RpcResponse; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.Socket; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/14 17:39 - */ -@AllArgsConstructor -public class WorkThread implements Runnable{ - private Socket socket; - private ServiceProvider serviceProvide; - @Override - public void run() { - try { - ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream()); - ObjectInputStream ois=new ObjectInputStream(socket.getInputStream()); - //读取客户端传过来的request - RpcRequest rpcRequest = (RpcRequest) ois.readObject(); - //反射调用服务方法获取返回值 - RpcResponse rpcResponse=getResponse(rpcRequest); - //向客户端写入response - oos.writeObject(rpcResponse); - oos.flush(); - } catch (IOException | ClassNotFoundException e) { - e.printStackTrace(); - } - } - private RpcResponse getResponse(RpcRequest rpcRequest){ - //得到服务名 - String interfaceName=rpcRequest.getInterfaceName(); - //得到服务端相应服务实现类 - Object service = serviceProvide.getService(interfaceName); - //反射调用方法 - Method method=null; - try { - method= service.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParamsType()); - Object invoke=method.invoke(service,rpcRequest.getParams()); - return RpcResponse.sussess(invoke); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - e.printStackTrace(); - System.out.println("方法执行错误"); - return RpcResponse.fail(); - } - } -} diff --git a/version1/src/main/java/part1/common/Message/RpcRequest.java b/version1/src/main/java/part1/common/Message/RpcRequest.java deleted file mode 100644 index 0d8f171..0000000 --- a/version1/src/main/java/part1/common/Message/RpcRequest.java +++ /dev/null @@ -1,25 +0,0 @@ -package part1.common.Message; - -import lombok.Builder; -import lombok.Data; - -import java.io.Serializable; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/1 18:30 - * 定义发送的消息格式 - */ -@Data -@Builder -public class RpcRequest implements Serializable { - //服务类名,客户端只知道接口 - private String interfaceName; - //调用的方法名 - private String methodName; - //参数列表 - private Object[] params; - //参数类型 - private Class[] paramsType; -} diff --git a/version1/src/main/java/part1/common/Message/RpcResponse.java b/version1/src/main/java/part1/common/Message/RpcResponse.java deleted file mode 100644 index 906ee1c..0000000 --- a/version1/src/main/java/part1/common/Message/RpcResponse.java +++ /dev/null @@ -1,30 +0,0 @@ -package part1.common.Message; - -import lombok.Builder; -import lombok.Data; - -import java.io.Serializable; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/1 19:18 - */ -@Data -@Builder -public class RpcResponse implements Serializable { - //状态信息 - private int code; - private String message; - //具体数据 - private Object data; - //构造成功信息 - public static RpcResponse sussess(Object data){ - return RpcResponse.builder().code(200).data(data).build(); - } - //构造失败信息 - public static RpcResponse fail(){ - return RpcResponse.builder().code(500).message("服务器发生错误").build(); - } -} - diff --git a/version1/src/main/java/part1/common/pojo/User.java b/version1/src/main/java/part1/common/pojo/User.java deleted file mode 100644 index d7cef8c..0000000 --- a/version1/src/main/java/part1/common/pojo/User.java +++ /dev/null @@ -1,25 +0,0 @@ -package part1.common.pojo; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.io.Serializable; - -/** - * @author wxx - * @version 1.0 - * @create 2024/1/28 17:50 - */ -@Builder -@Data -@NoArgsConstructor -@AllArgsConstructor -public class User implements Serializable { - // 客户端和服务端共有的 - private Integer id; - private String userName; - private Boolean sex; -} - diff --git a/version1/src/main/java/part1/common/service/Impl/UserServiceImpl.java b/version1/src/main/java/part1/common/service/Impl/UserServiceImpl.java deleted file mode 100644 index 373243b..0000000 --- a/version1/src/main/java/part1/common/service/Impl/UserServiceImpl.java +++ /dev/null @@ -1,32 +0,0 @@ -package part1.common.service.Impl; - - -import part1.common.pojo.User; -import part1.common.service.UserService; - -import java.util.Random; -import java.util.UUID; - -/** - * @author wxx - * @version 1.0 - * @create 2024/1/28 16:28 - */ -public class UserServiceImpl implements UserService { - @Override - public User getUserByUserId(Integer id) { - System.out.println("客户端查询了"+id+"的用户"); - // 模拟从数据库中取用户的行为 - Random random = new Random(); - User user = User.builder().userName(UUID.randomUUID().toString()) - .id(id) - .sex(random.nextBoolean()).build(); - return user; - } - - @Override - public Integer insertUserId(User user) { - System.out.println("插入数据成功"+user.getUserName()); - return user.getId(); - } -} \ No newline at end of file diff --git a/version1/src/main/java/part1/common/service/UserService.java b/version1/src/main/java/part1/common/service/UserService.java deleted file mode 100644 index 0e539bd..0000000 --- a/version1/src/main/java/part1/common/service/UserService.java +++ /dev/null @@ -1,16 +0,0 @@ -package part1.common.service; - - -import part1.common.pojo.User; - -/** - * @author wxx - * @version 1.0 - * @create 2024/1/28 16:27 - */ -public interface UserService { - // 客户端通过这个接口调用服务端的实现类 - User getUserByUserId(Integer id); - //新增一个功能 - Integer insertUserId(User user); -} diff --git a/version1/src/main/java/part2/Client/IOClient.java b/version1/src/main/java/part2/Client/IOClient.java deleted file mode 100644 index 066736a..0000000 --- a/version1/src/main/java/part2/Client/IOClient.java +++ /dev/null @@ -1,36 +0,0 @@ -package part2.Client; - - - -import part2.common.Message.RpcRequest; -import part2.common.Message.RpcResponse; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.net.Socket; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/4 18:31 - */ -public class IOClient { - //这里负责底层与服务端的通信,发送request,返回response - public static RpcResponse sendRequest(String host, int port, RpcRequest request){ - try { - Socket socket=new Socket(host, port); - ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream()); - ObjectInputStream ois=new ObjectInputStream(socket.getInputStream()); - - oos.writeObject(request); - oos.flush(); - - RpcResponse response=(RpcResponse) ois.readObject(); - return response; - } catch (IOException | ClassNotFoundException e) { - e.printStackTrace(); - return null; - } - } -} diff --git a/version1/src/main/java/part2/Client/TestClient.java b/version1/src/main/java/part2/Client/TestClient.java deleted file mode 100644 index 3ce5d38..0000000 --- a/version1/src/main/java/part2/Client/TestClient.java +++ /dev/null @@ -1,26 +0,0 @@ -package part2.Client; - - -import part2.Client.proxy.ClientProxy; -import part2.common.pojo.User; -import part2.common.service.UserService; - - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/6 18:39 - */ -public class TestClient { - public static void main(String[] args) { - ClientProxy clientProxy=new ClientProxy("127.0.0.1",9999,0); - UserService proxy=clientProxy.getProxy(UserService.class); - - User user = proxy.getUserByUserId(1); - System.out.println("从服务端得到的user="+user.toString()); - - User u=User.builder().id(100).userName("wxx").sex(true).build(); - Integer id = proxy.insertUserId(u); - System.out.println("向服务端插入user的id"+id); - } -} diff --git a/version1/src/main/java/part2/Client/netty/handler/NettyClientHandler.java b/version1/src/main/java/part2/Client/netty/handler/NettyClientHandler.java deleted file mode 100644 index 12d5693..0000000 --- a/version1/src/main/java/part2/Client/netty/handler/NettyClientHandler.java +++ /dev/null @@ -1,28 +0,0 @@ -package part2.Client.netty.handler; - -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.SimpleChannelInboundHandler; -import io.netty.util.AttributeKey; -import part2.common.Message.RpcResponse; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/26 17:29 - */ -public class NettyClientHandler extends SimpleChannelInboundHandler { - @Override - protected void channelRead0(ChannelHandlerContext ctx, RpcResponse response) throws Exception { - // 接收到response, 给channel设计别名,让sendRequest里读取response - AttributeKey key = AttributeKey.valueOf("RPCResponse"); - ctx.channel().attr(key).set(response); - ctx.channel().close(); - } - - @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { - //异常处理 - cause.printStackTrace(); - ctx.close(); - } -} diff --git a/version1/src/main/java/part2/Client/netty/nettyInitializer/NettyClientInitializer.java b/version1/src/main/java/part2/Client/netty/nettyInitializer/NettyClientInitializer.java deleted file mode 100644 index 5bec33d..0000000 --- a/version1/src/main/java/part2/Client/netty/nettyInitializer/NettyClientInitializer.java +++ /dev/null @@ -1,43 +0,0 @@ -package part2.Client.netty.nettyInitializer; - - -import io.netty.channel.ChannelInitializer; -import io.netty.channel.ChannelPipeline; -import io.netty.channel.socket.SocketChannel; -import io.netty.handler.codec.LengthFieldBasedFrameDecoder; -import io.netty.handler.codec.LengthFieldPrepender; -import io.netty.handler.codec.serialization.ClassResolver; -import io.netty.handler.codec.serialization.ObjectDecoder; -import io.netty.handler.codec.serialization.ObjectEncoder; -import part2.Client.netty.handler.NettyClientHandler; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/26 17:26 - */ -public class NettyClientInitializer extends ChannelInitializer { - @Override - protected void initChannel(SocketChannel ch) throws Exception { - ChannelPipeline pipeline = ch.pipeline(); - //消息格式 【长度】【消息体】,解决沾包问题 - pipeline.addLast( - new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0,4,0,4)); - //计算当前待发送消息的长度,写入到前4个字节中 - pipeline.addLast(new LengthFieldPrepender(4)); - //编码器 - //使用Java序列化方式,netty的自带的解码编码支持传输这种结构 - pipeline.addLast(new ObjectEncoder()); - //解码器 - //使用了Netty中的ObjectDecoder,它用于将字节流解码为 Java 对象。 - //在ObjectDecoder的构造函数中传入了一个ClassResolver 对象,用于解析类名并加载相应的类。 - pipeline.addLast(new ObjectDecoder(new ClassResolver() { - @Override - public Class resolve(String className) throws ClassNotFoundException { - return Class.forName(className); - } - })); - - pipeline.addLast(new NettyClientHandler()); - } -} diff --git a/version1/src/main/java/part2/Client/proxy/ClientProxy.java b/version1/src/main/java/part2/Client/proxy/ClientProxy.java deleted file mode 100644 index a6b5a4e..0000000 --- a/version1/src/main/java/part2/Client/proxy/ClientProxy.java +++ /dev/null @@ -1,53 +0,0 @@ -package part2.Client.proxy; - - -import lombok.AllArgsConstructor; -import part2.common.Message.RpcRequest; -import part2.common.Message.RpcResponse; -import part2.Client.IOClient; -import part2.Client.rpcClient.RpcClient; -import part2.Client.rpcClient.impl.NettyRpcClient; -import part2.Client.rpcClient.impl.SimpleSocketRpcCilent; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/6 16:49 - */ -public class ClientProxy implements InvocationHandler { - //传入参数service接口的class对象,反射封装成一个request - - private RpcClient rpcClient; - public ClientProxy(String host,int port,int choose){ - switch (choose){ - case 0: - rpcClient=new NettyRpcClient(host,port); - break; - case 1: - rpcClient=new SimpleSocketRpcCilent(host,port); - } - } - public ClientProxy(String host,int port){ - rpcClient=new NettyRpcClient(host,port); - } - //jdk动态代理,每一次代理对象调用方法,都会经过此方法增强(反射获取request对象,socket发送到服务端) - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - //构建request - RpcRequest request=RpcRequest.builder() - .interfaceName(method.getDeclaringClass().getName()) - .methodName(method.getName()) - .params(args).paramsType(method.getParameterTypes()).build(); - //数据传输 - RpcResponse response= rpcClient.sendRequest(request); - return response.getData(); - } - public T getProxy(Class clazz){ - Object o = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, this); - return (T)o; - } -} diff --git a/version1/src/main/java/part2/Client/rpcClient/RpcClient.java b/version1/src/main/java/part2/Client/rpcClient/RpcClient.java deleted file mode 100644 index 21690b1..0000000 --- a/version1/src/main/java/part2/Client/rpcClient/RpcClient.java +++ /dev/null @@ -1,15 +0,0 @@ -package part2.Client.rpcClient; - -import part2.common.Message.RpcRequest; -import part2.common.Message.RpcResponse; - -/** - * @author wxx - * @version 1.0 - * @create 2024/5/2 18:55 - */ -public interface RpcClient { - - //定义底层通信的方法 - RpcResponse sendRequest(RpcRequest request); -} diff --git a/version1/src/main/java/part2/Client/rpcClient/impl/NettyRpcClient.java b/version1/src/main/java/part2/Client/rpcClient/impl/NettyRpcClient.java deleted file mode 100644 index b3dab27..0000000 --- a/version1/src/main/java/part2/Client/rpcClient/impl/NettyRpcClient.java +++ /dev/null @@ -1,62 +0,0 @@ -package part2.Client.rpcClient.impl; - -import io.netty.bootstrap.Bootstrap; -import io.netty.channel.Channel; -import io.netty.channel.ChannelFuture; -import io.netty.channel.EventLoopGroup; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.nio.NioSocketChannel; -import io.netty.util.AttributeKey; -import part2.Client.netty.nettyInitializer.NettyClientInitializer; -import part2.common.Message.RpcRequest; -import part2.common.Message.RpcResponse; -import part2.Client.rpcClient.RpcClient; - -/** - * @author wxx - * @version 1.0 - * @create 2024/5/2 19:40 - */ -public class NettyRpcClient implements RpcClient { - private String host; - private int port; - private static final Bootstrap bootstrap; - private static final EventLoopGroup eventLoopGroup; - public NettyRpcClient(String host,int port){ - this.host=host; - this.port=port; - } - //netty客户端初始化 - static { - eventLoopGroup = new NioEventLoopGroup(); - bootstrap = new Bootstrap(); - bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class) - //NettyClientInitializer这里 配置netty对消息的处理机制 - .handler(new NettyClientInitializer()); - } - @Override - public RpcResponse sendRequest(RpcRequest request) { - try { - //创建一个channelFuture对象,代表这一个操作事件,sync方法表示堵塞直到connect完成 - ChannelFuture channelFuture = bootstrap.connect(host, port).sync(); - //channel表示一个连接的单位,类似socket - Channel channel = channelFuture.channel(); - // 发送数据 - channel.writeAndFlush(request); - //sync()堵塞获取结果 - channel.closeFuture().sync(); - // 阻塞的获得结果,通过给channel设计别名,获取特定名字下的channel中的内容(这个在hanlder中设置) - // AttributeKey是,线程隔离的,不会由线程安全问题。 - // 当前场景下选择堵塞获取结果 - // 其它场景也可以选择添加监听器的方式来异步获取结果 channelFuture.addListener... - AttributeKey key = AttributeKey.valueOf("RPCResponse"); - RpcResponse response = channel.attr(key).get(); - - System.out.println(response); - return response; - } catch (InterruptedException e) { - e.printStackTrace(); - } - return null; - } -} diff --git a/version1/src/main/java/part2/Client/rpcClient/impl/SimpleSocketRpcCilent.java b/version1/src/main/java/part2/Client/rpcClient/impl/SimpleSocketRpcCilent.java deleted file mode 100644 index 7e9f09c..0000000 --- a/version1/src/main/java/part2/Client/rpcClient/impl/SimpleSocketRpcCilent.java +++ /dev/null @@ -1,41 +0,0 @@ -package part2.Client.rpcClient.impl; - -import part2.common.Message.RpcRequest; -import part2.common.Message.RpcResponse; -import part2.Client.rpcClient.RpcClient; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.net.Socket; - -/** - * @author wxx - * @version 1.0 - * @create 2024/5/2 18:58 - */ -public class SimpleSocketRpcCilent implements RpcClient { - private String host; - private int port; - public SimpleSocketRpcCilent(String host,int port){ - this.host=host; - this.port=port; - } - @Override - public RpcResponse sendRequest(RpcRequest request) { - try { - Socket socket=new Socket(host, port); - ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream()); - ObjectInputStream ois=new ObjectInputStream(socket.getInputStream()); - - oos.writeObject(request); - oos.flush(); - - RpcResponse response=(RpcResponse) ois.readObject(); - return response; - } catch (IOException | ClassNotFoundException e) { - e.printStackTrace(); - return null; - } - } -} diff --git a/version1/src/main/java/part2/Server/TestServer.java b/version1/src/main/java/part2/Server/TestServer.java deleted file mode 100644 index a055f3e..0000000 --- a/version1/src/main/java/part2/Server/TestServer.java +++ /dev/null @@ -1,26 +0,0 @@ -package part2.Server; - - -import part2.Server.server.impl.NettyRPCRPCServer; -import part2.common.service.Impl.UserServiceImpl; -import part2.common.service.UserService; -import part2.Server.provider.ServiceProvider; -import part2.Server.server.RpcServer; -import part2.Server.server.impl.SimpleRPCRPCServer; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/11 19:39 - */ -public class TestServer { - public static void main(String[] args) { - UserService userService=new UserServiceImpl(); - - ServiceProvider serviceProvider=new ServiceProvider(); - serviceProvider.provideServiceInterface(userService); - - RpcServer rpcServer=new NettyRPCRPCServer(serviceProvider); - rpcServer.start(9999); - } -} diff --git a/version1/src/main/java/part2/Server/netty/handler/NettyRPCServerHandler.java b/version1/src/main/java/part2/Server/netty/handler/NettyRPCServerHandler.java deleted file mode 100644 index 14948cc..0000000 --- a/version1/src/main/java/part2/Server/netty/handler/NettyRPCServerHandler.java +++ /dev/null @@ -1,52 +0,0 @@ -package part2.Server.netty.handler; - -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.SimpleChannelInboundHandler; -import lombok.AllArgsConstructor; -import part2.Server.provider.ServiceProvider; -import part2.common.Message.RpcRequest; -import part2.common.Message.RpcResponse; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/26 16:40 - * 因为是服务器端,我们知道接受到请求格式是RPCRequest - * Object类型也行,强制转型就行 - */ -@AllArgsConstructor -public class NettyRPCServerHandler extends SimpleChannelInboundHandler { - private ServiceProvider serviceProvider; - @Override - protected void channelRead0(ChannelHandlerContext ctx, RpcRequest request) throws Exception { - //接收request,读取并调用服务 - RpcResponse response = getResponse(request); - ctx.writeAndFlush(response); - ctx.close(); - } - @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { - cause.printStackTrace(); - ctx.close(); - } - private RpcResponse getResponse(RpcRequest rpcRequest){ - //得到服务名 - String interfaceName=rpcRequest.getInterfaceName(); - //得到服务端相应服务实现类 - Object service = serviceProvider.getService(interfaceName); - //反射调用方法 - Method method=null; - try { - method= service.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParamsType()); - Object invoke=method.invoke(service,rpcRequest.getParams()); - return RpcResponse.sussess(invoke); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - e.printStackTrace(); - System.out.println("方法执行错误"); - return RpcResponse.fail(); - } - } -} diff --git a/version1/src/main/java/part2/Server/netty/nettyInitializer/NettyServerInitializer.java b/version1/src/main/java/part2/Server/netty/nettyInitializer/NettyServerInitializer.java deleted file mode 100644 index 254b04c..0000000 --- a/version1/src/main/java/part2/Server/netty/nettyInitializer/NettyServerInitializer.java +++ /dev/null @@ -1,46 +0,0 @@ -package part2.Server.netty.nettyInitializer; - - -import io.netty.channel.ChannelInitializer; -import io.netty.channel.ChannelPipeline; -import io.netty.channel.socket.SocketChannel; -import io.netty.handler.codec.LengthFieldBasedFrameDecoder; -import io.netty.handler.codec.LengthFieldPrepender; -import io.netty.handler.codec.serialization.ClassResolver; -import io.netty.handler.codec.serialization.ObjectDecoder; -import io.netty.handler.codec.serialization.ObjectEncoder; -import lombok.AllArgsConstructor; -import part2.Server.netty.handler.NettyRPCServerHandler; -import part2.Server.provider.ServiceProvider; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/26 16:15 - */ -@AllArgsConstructor -public class NettyServerInitializer extends ChannelInitializer { - private ServiceProvider serviceProvider; - @Override - protected void initChannel(SocketChannel ch) throws Exception { - ChannelPipeline pipeline = ch.pipeline(); - //消息格式 【长度】【消息体】,解决沾包问题 - pipeline.addLast( - new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0,4,0,4)); - //计算当前待发送消息的长度,写入到前4个字节中 - pipeline.addLast(new LengthFieldPrepender(4)); - - //使用Java序列化方式,netty的自带的解码编码支持传输这种结构 - pipeline.addLast(new ObjectEncoder()); - //使用了Netty中的ObjectDecoder,它用于将字节流解码为 Java 对象。 - //在ObjectDecoder的构造函数中传入了一个ClassResolver 对象,用于解析类名并加载相应的类。 - pipeline.addLast(new ObjectDecoder(new ClassResolver() { - @Override - public Class resolve(String className) throws ClassNotFoundException { - return Class.forName(className); - } - })); - - pipeline.addLast(new NettyRPCServerHandler(serviceProvider)); - } -} diff --git a/version1/src/main/java/part2/Server/provider/ServiceProvider.java b/version1/src/main/java/part2/Server/provider/ServiceProvider.java deleted file mode 100644 index 5cee41f..0000000 --- a/version1/src/main/java/part2/Server/provider/ServiceProvider.java +++ /dev/null @@ -1,32 +0,0 @@ -package part2.Server.provider; - -import java.util.HashMap; -import java.util.Map; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/16 17:35 - */ -public class ServiceProvider { - private Map interfaceProvider; - - public ServiceProvider(){ - this.interfaceProvider=new HashMap<>(); - } - - public void provideServiceInterface(Object service){ - String serviceName=service.getClass().getName(); - Class[] interfaceName=service.getClass().getInterfaces(); - - for (Class clazz:interfaceName){ - interfaceProvider.put(clazz.getName(),service); - } - - } - - public Object getService(String interfaceName){ - return interfaceProvider.get(interfaceName); - } - -} diff --git a/version1/src/main/java/part2/Server/server/RpcServer.java b/version1/src/main/java/part2/Server/server/RpcServer.java deleted file mode 100644 index 6abbf2a..0000000 --- a/version1/src/main/java/part2/Server/server/RpcServer.java +++ /dev/null @@ -1,11 +0,0 @@ -package part2.Server.server; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/12 11:26 - */ -public interface RpcServer { - void start(int port); - void stop(); -} diff --git a/version1/src/main/java/part2/Server/server/impl/NettyRPCRPCServer.java b/version1/src/main/java/part2/Server/server/impl/NettyRPCRPCServer.java deleted file mode 100644 index 97632a6..0000000 --- a/version1/src/main/java/part2/Server/server/impl/NettyRPCRPCServer.java +++ /dev/null @@ -1,49 +0,0 @@ -package part2.Server.server.impl; - -import io.netty.bootstrap.ServerBootstrap; -import io.netty.channel.ChannelFuture; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.nio.NioServerSocketChannel; -import lombok.AllArgsConstructor; -import part2.Server.netty.nettyInitializer.NettyServerInitializer; -import part2.Server.provider.ServiceProvider; -import part2.Server.server.RpcServer; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/26 14:01 - */ -@AllArgsConstructor -public class NettyRPCRPCServer implements RpcServer { - private ServiceProvider serviceProvider; - @Override - public void start(int port) { - // netty 服务线程组boss负责建立连接, work负责具体的请求 - NioEventLoopGroup bossGroup = new NioEventLoopGroup(); - NioEventLoopGroup workGroup = new NioEventLoopGroup(); - System.out.println("netty服务端启动了"); - try { - //启动netty服务器 - ServerBootstrap serverBootstrap = new ServerBootstrap(); - //初始化 - serverBootstrap.group(bossGroup,workGroup).channel(NioServerSocketChannel.class) - //NettyClientInitializer这里 配置netty对消息的处理机制 - .childHandler(new NettyServerInitializer(serviceProvider)); - //同步堵塞 - ChannelFuture channelFuture=serverBootstrap.bind(port).sync(); - //死循环监听 - channelFuture.channel().closeFuture().sync(); - }catch (InterruptedException e){ - e.printStackTrace(); - }finally { - bossGroup.shutdownGracefully(); - workGroup.shutdownGracefully(); - } - } - - @Override - public void stop() { - - } -} diff --git a/version1/src/main/java/part2/Server/server/impl/SimpleRPCRPCServer.java b/version1/src/main/java/part2/Server/server/impl/SimpleRPCRPCServer.java deleted file mode 100644 index 8033bab..0000000 --- a/version1/src/main/java/part2/Server/server/impl/SimpleRPCRPCServer.java +++ /dev/null @@ -1,39 +0,0 @@ -package part2.Server.server.impl; - - -import lombok.AllArgsConstructor; -import part2.Server.provider.ServiceProvider; -import part2.Server.server.RpcServer; -import part2.Server.server.work.WorkThread; - -import java.io.IOException; -import java.net.ServerSocket; -import java.net.Socket; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/12 11:37 - */ -@AllArgsConstructor -public class SimpleRPCRPCServer implements RpcServer { - private ServiceProvider serviceProvide; - @Override - public void start(int port) { - try { - ServerSocket serverSocket=new ServerSocket(port); - System.out.println("服务器启动了"); - while (true) { - Socket socket = serverSocket.accept(); - new Thread(new WorkThread(socket,serviceProvide)).start(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Override - public void stop() { - - } -} diff --git a/version1/src/main/java/part2/Server/server/impl/ThreadPoolRPCRPCServer.java b/version1/src/main/java/part2/Server/server/impl/ThreadPoolRPCRPCServer.java deleted file mode 100644 index 834c9a5..0000000 --- a/version1/src/main/java/part2/Server/server/impl/ThreadPoolRPCRPCServer.java +++ /dev/null @@ -1,58 +0,0 @@ -package part2.Server.server.impl; - - -import part2.Server.provider.ServiceProvider; -import part2.Server.server.RpcServer; -import part2.Server.server.work.WorkThread; - -import java.io.IOException; -import java.net.ServerSocket; -import java.net.Socket; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/19 15:30 - */ -public class ThreadPoolRPCRPCServer implements RpcServer { - private final ThreadPoolExecutor threadPool; - private ServiceProvider serviceProvider; - - public ThreadPoolRPCRPCServer(ServiceProvider serviceProvider){ - threadPool=new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), - 1000,60, TimeUnit.SECONDS,new ArrayBlockingQueue<>(100)); - this.serviceProvider= serviceProvider; - } - public ThreadPoolRPCRPCServer(ServiceProvider serviceProvider, int corePoolSize, - int maximumPoolSize, - long keepAliveTime, - TimeUnit unit, - BlockingQueue workQueue){ - - threadPool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue); - this.serviceProvider = serviceProvider; - } - - @Override - public void start(int port) { - System.out.println("服务端启动了"); - try { - ServerSocket serverSocket=new ServerSocket(); - while (true){ - Socket socket= serverSocket.accept(); - threadPool.execute(new WorkThread(socket,serviceProvider)); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Override - public void stop() { - - } -} diff --git a/version1/src/main/java/part2/Server/server/work/WorkThread.java b/version1/src/main/java/part2/Server/server/work/WorkThread.java deleted file mode 100644 index a3985bf..0000000 --- a/version1/src/main/java/part2/Server/server/work/WorkThread.java +++ /dev/null @@ -1,58 +0,0 @@ -package part2.Server.server.work; - - -import lombok.AllArgsConstructor; -import part2.Server.provider.ServiceProvider; -import part2.common.Message.RpcRequest; -import part2.common.Message.RpcResponse; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.Socket; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/14 17:39 - */ -@AllArgsConstructor -public class WorkThread implements Runnable{ - private Socket socket; - private ServiceProvider serviceProvide; - @Override - public void run() { - try { - ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream()); - ObjectInputStream ois=new ObjectInputStream(socket.getInputStream()); - //读取客户端传过来的request - RpcRequest rpcRequest = (RpcRequest) ois.readObject(); - //反射调用服务方法获取返回值 - RpcResponse rpcResponse=getResponse(rpcRequest); - //向客户端写入response - oos.writeObject(rpcResponse); - oos.flush(); - } catch (IOException | ClassNotFoundException e) { - e.printStackTrace(); - } - } - private RpcResponse getResponse(RpcRequest rpcRequest){ - //得到服务名 - String interfaceName=rpcRequest.getInterfaceName(); - //得到服务端相应服务实现类 - Object service = serviceProvide.getService(interfaceName); - //反射调用方法 - Method method=null; - try { - method= service.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParamsType()); - Object invoke=method.invoke(service,rpcRequest.getParams()); - return RpcResponse.sussess(invoke); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - e.printStackTrace(); - System.out.println("方法执行错误"); - return RpcResponse.fail(); - } - } -} diff --git a/version1/src/main/java/part2/common/Message/RpcRequest.java b/version1/src/main/java/part2/common/Message/RpcRequest.java deleted file mode 100644 index f6f398d..0000000 --- a/version1/src/main/java/part2/common/Message/RpcRequest.java +++ /dev/null @@ -1,25 +0,0 @@ -package part2.common.Message; - -import lombok.Builder; -import lombok.Data; - -import java.io.Serializable; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/1 18:30 - * 定义发送的消息格式 - */ -@Data -@Builder -public class RpcRequest implements Serializable { - //服务类名,客户端只知道接口 - private String interfaceName; - //调用的方法名 - private String methodName; - //参数列表 - private Object[] params; - //参数类型 - private Class[] paramsType; -} diff --git a/version1/src/main/java/part2/common/Message/RpcResponse.java b/version1/src/main/java/part2/common/Message/RpcResponse.java deleted file mode 100644 index a681df8..0000000 --- a/version1/src/main/java/part2/common/Message/RpcResponse.java +++ /dev/null @@ -1,29 +0,0 @@ -package part2.common.Message; - -import lombok.Builder; -import lombok.Data; - -import java.io.Serializable; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/1 19:18 - */ -@Data -@Builder -public class RpcResponse implements Serializable { - //状态信息 - private int code; - private String message; - //具体数据 - private Object data; - - public static RpcResponse sussess(Object data){ - return RpcResponse.builder().code(200).data(data).build(); - } - public static RpcResponse fail(){ - return RpcResponse.builder().code(500).message("服务器发生错误").build(); - } -} - diff --git a/version1/src/main/java/part2/common/pojo/User.java b/version1/src/main/java/part2/common/pojo/User.java deleted file mode 100644 index bf999d7..0000000 --- a/version1/src/main/java/part2/common/pojo/User.java +++ /dev/null @@ -1,25 +0,0 @@ -package part2.common.pojo; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.io.Serializable; - -/** - * @author wxx - * @version 1.0 - * @create 2024/1/28 17:50 - */ -@Builder -@Data -@NoArgsConstructor -@AllArgsConstructor -public class User implements Serializable { - // 客户端和服务端共有的 - private Integer id; - private String userName; - private Boolean sex; -} - diff --git a/version1/src/main/java/part2/common/service/Impl/UserServiceImpl.java b/version1/src/main/java/part2/common/service/Impl/UserServiceImpl.java deleted file mode 100644 index 37e6262..0000000 --- a/version1/src/main/java/part2/common/service/Impl/UserServiceImpl.java +++ /dev/null @@ -1,32 +0,0 @@ -package part2.common.service.Impl; - - -import part2.common.pojo.User; -import part2.common.service.UserService; - -import java.util.Random; -import java.util.UUID; - -/** - * @author wxx - * @version 1.0 - * @create 2024/1/28 16:28 - */ -public class UserServiceImpl implements UserService { - @Override - public User getUserByUserId(Integer id) { - System.out.println("客户端查询了"+id+"的用户"); - // 模拟从数据库中取用户的行为 - Random random = new Random(); - User user = User.builder().userName(UUID.randomUUID().toString()) - .id(id) - .sex(random.nextBoolean()).build(); - return user; - } - - @Override - public Integer insertUserId(User user) { - System.out.println("插入数据成功"+user.getUserName()); - return user.getId(); - } -} \ No newline at end of file diff --git a/version1/src/main/java/part3/Client/TestClient.java b/version1/src/main/java/part3/Client/TestClient.java deleted file mode 100644 index 5408350..0000000 --- a/version1/src/main/java/part3/Client/TestClient.java +++ /dev/null @@ -1,29 +0,0 @@ -package part3.Client; - - -import lombok.extern.slf4j.Slf4j; -import part3.common.pojo.User; -import part3.common.service.UserService; -import part3.Client.proxy.ClientProxy; - - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/6 18:39 - */ - -public class TestClient { - public static void main(String[] args) { - ClientProxy clientProxy=new ClientProxy(); - //ClientProxy clientProxy=new part2.Client.proxy.ClientProxy("127.0.0.1",9999,0); - UserService proxy=clientProxy.getProxy(UserService.class); - - User user = proxy.getUserByUserId(1); - System.out.println("从服务端得到的user="+user.toString()); - - User u=User.builder().id(100).userName("wxx").sex(true).build(); - Integer id = proxy.insertUserId(u); - System.out.println("向服务端插入user的id"+id); - } -} diff --git a/version1/src/main/java/part3/Client/netty/handler/NettyClientHandler.java b/version1/src/main/java/part3/Client/netty/handler/NettyClientHandler.java deleted file mode 100644 index 28f173e..0000000 --- a/version1/src/main/java/part3/Client/netty/handler/NettyClientHandler.java +++ /dev/null @@ -1,27 +0,0 @@ -package part3.Client.netty.handler; - -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.SimpleChannelInboundHandler; -import io.netty.util.AttributeKey; -import part3.common.Message.RpcResponse; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/26 17:29 - */ -public class NettyClientHandler extends SimpleChannelInboundHandler { - @Override - protected void channelRead0(ChannelHandlerContext ctx, RpcResponse response) throws Exception { - // 接收到response, 给channel设计别名,让sendRequest里读取response - AttributeKey key = AttributeKey.valueOf("RPCResponse"); - ctx.channel().attr(key).set(response); - ctx.channel().close(); - } - - @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { - cause.printStackTrace(); - ctx.close(); - } -} diff --git a/version1/src/main/java/part3/Client/netty/nettyInitializer/NettyClientInitializer.java b/version1/src/main/java/part3/Client/netty/nettyInitializer/NettyClientInitializer.java deleted file mode 100644 index bca4a4c..0000000 --- a/version1/src/main/java/part3/Client/netty/nettyInitializer/NettyClientInitializer.java +++ /dev/null @@ -1,42 +0,0 @@ -package part3.Client.netty.nettyInitializer; - - -import io.netty.channel.ChannelInitializer; -import io.netty.channel.ChannelPipeline; -import io.netty.channel.socket.SocketChannel; -import io.netty.handler.codec.LengthFieldBasedFrameDecoder; -import io.netty.handler.codec.LengthFieldPrepender; -import io.netty.handler.codec.serialization.ClassResolver; -import io.netty.handler.codec.serialization.ObjectDecoder; -import io.netty.handler.codec.serialization.ObjectEncoder; -import part3.Client.netty.handler.NettyClientHandler; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/26 17:26 - */ -public class NettyClientInitializer extends ChannelInitializer { - @Override - protected void initChannel(SocketChannel ch) throws Exception { - ChannelPipeline pipeline = ch.pipeline(); - //消息格式 【长度】【消息体】,解决沾包问题 - pipeline.addLast( - new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0,4,0,4)); - //计算当前待发送消息的长度,写入到前4个字节中 - pipeline.addLast(new LengthFieldPrepender(4)); - - //使用Java序列化方式,netty的自带的解码编码支持传输这种结构 - pipeline.addLast(new ObjectEncoder()); - //使用了Netty中的ObjectDecoder,它用于将字节流解码为 Java 对象。 - //在ObjectDecoder的构造函数中传入了一个ClassResolver 对象,用于解析类名并加载相应的类。 - pipeline.addLast(new ObjectDecoder(new ClassResolver() { - @Override - public Class resolve(String className) throws ClassNotFoundException { - return Class.forName(className); - } - })); - - pipeline.addLast(new NettyClientHandler()); - } -} diff --git a/version1/src/main/java/part3/Client/proxy/ClientProxy.java b/version1/src/main/java/part3/Client/proxy/ClientProxy.java deleted file mode 100644 index 8cb957e..0000000 --- a/version1/src/main/java/part3/Client/proxy/ClientProxy.java +++ /dev/null @@ -1,43 +0,0 @@ -package part3.Client.proxy; - - -import part3.common.Message.RpcRequest; -import part3.common.Message.RpcResponse; -import part3.Client.rpcClient.RpcClient; -import part3.Client.rpcClient.impl.NettyRpcClient; -import part3.Client.rpcClient.impl.SimpleSocketRpcCilent; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/6 16:49 - */ -public class ClientProxy implements InvocationHandler { - //传入参数service接口的class对象,反射封装成一个request - - private RpcClient rpcClient; - public ClientProxy(){ - rpcClient=new NettyRpcClient(); - } - - //jdk动态代理,每一次代理对象调用方法,都会经过此方法增强(反射获取request对象,socket发送到服务端) - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - //构建request - RpcRequest request=RpcRequest.builder() - .interfaceName(method.getDeclaringClass().getName()) - .methodName(method.getName()) - .params(args).paramsType(method.getParameterTypes()).build(); - //数据传输 - RpcResponse response= rpcClient.sendRequest(request); - return response.getData(); - } - public T getProxy(Class clazz){ - Object o = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, this); - return (T)o; - } -} diff --git a/version1/src/main/java/part3/Client/rpcClient/RpcClient.java b/version1/src/main/java/part3/Client/rpcClient/RpcClient.java deleted file mode 100644 index 44b702b..0000000 --- a/version1/src/main/java/part3/Client/rpcClient/RpcClient.java +++ /dev/null @@ -1,15 +0,0 @@ -package part3.Client.rpcClient; - -import part3.common.Message.RpcRequest; -import part3.common.Message.RpcResponse; - -/** - * @author wxx - * @version 1.0 - * @create 2024/5/2 18:55 - */ -public interface RpcClient { - - //定义底层通信的方法 - RpcResponse sendRequest(RpcRequest request); -} diff --git a/version1/src/main/java/part3/Client/rpcClient/impl/NettyRpcClient.java b/version1/src/main/java/part3/Client/rpcClient/impl/NettyRpcClient.java deleted file mode 100644 index a4fc493..0000000 --- a/version1/src/main/java/part3/Client/rpcClient/impl/NettyRpcClient.java +++ /dev/null @@ -1,68 +0,0 @@ -package part3.Client.rpcClient.impl; - -import io.netty.bootstrap.Bootstrap; -import io.netty.channel.Channel; -import io.netty.channel.ChannelFuture; -import io.netty.channel.EventLoopGroup; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.nio.NioSocketChannel; -import io.netty.util.AttributeKey; -import part3.Client.serviceCenter.ServiceCenter; -import part3.Client.serviceCenter.ZKServiceCenter; -import part3.common.Message.RpcRequest; -import part3.common.Message.RpcResponse; -import part3.Client.netty.nettyInitializer.NettyClientInitializer; -import part3.Client.rpcClient.RpcClient; - -import java.net.InetSocketAddress; - -/** - * @author wxx - * @version 1.0 - * @create 2024/5/2 19:40 - */ -public class NettyRpcClient implements RpcClient { - - private static final Bootstrap bootstrap; - private static final EventLoopGroup eventLoopGroup; - - private ServiceCenter serviceCenter; - public NettyRpcClient(){ - this.serviceCenter=new ZKServiceCenter(); - } - - //netty客户端初始化 - static { - eventLoopGroup = new NioEventLoopGroup(); - bootstrap = new Bootstrap(); - bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class) - .handler(new NettyClientInitializer()); - } - @Override - public RpcResponse sendRequest(RpcRequest request) { - //从注册中心获取host,post - InetSocketAddress address = serviceCenter.serviceDiscovery(request.getInterfaceName()); - String host = address.getHostName(); - int port = address.getPort(); - try { - ChannelFuture channelFuture = bootstrap.connect(host, port).sync(); - Channel channel = channelFuture.channel(); - // 发送数据 - channel.writeAndFlush(request); - //sync()堵塞获取结果 - channel.closeFuture().sync(); - // 阻塞的获得结果,通过给channel设计别名,获取特定名字下的channel中的内容(这个在hanlder中设置) - // AttributeKey是,线程隔离的,不会由线程安全问题。 - // 当前场景下选择堵塞获取结果 - // 其它场景也可以选择添加监听器的方式来异步获取结果 channelFuture.addListener... - AttributeKey key = AttributeKey.valueOf("RPCResponse"); - RpcResponse response = channel.attr(key).get(); - - System.out.println(response); - return response; - } catch (InterruptedException e) { - e.printStackTrace(); - } - return null; - } -} diff --git a/version1/src/main/java/part3/Client/rpcClient/impl/SimpleSocketRpcCilent.java b/version1/src/main/java/part3/Client/rpcClient/impl/SimpleSocketRpcCilent.java deleted file mode 100644 index b2f6af3..0000000 --- a/version1/src/main/java/part3/Client/rpcClient/impl/SimpleSocketRpcCilent.java +++ /dev/null @@ -1,41 +0,0 @@ -package part3.Client.rpcClient.impl; - -import part3.common.Message.RpcRequest; -import part3.common.Message.RpcResponse; -import part3.Client.rpcClient.RpcClient; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.net.Socket; - -/** - * @author wxx - * @version 1.0 - * @create 2024/5/2 18:58 - */ -public class SimpleSocketRpcCilent implements RpcClient { - private String host; - private int port; - public SimpleSocketRpcCilent(String host,int port){ - this.host=host; - this.port=port; - } - @Override - public RpcResponse sendRequest(RpcRequest request) { - try { - Socket socket=new Socket(host, port); - ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream()); - ObjectInputStream ois=new ObjectInputStream(socket.getInputStream()); - - oos.writeObject(request); - oos.flush(); - - RpcResponse response=(RpcResponse) ois.readObject(); - return response; - } catch (IOException | ClassNotFoundException e) { - e.printStackTrace(); - return null; - } - } -} diff --git a/version1/src/main/java/part3/Client/serviceCenter/ServiceCenter.java b/version1/src/main/java/part3/Client/serviceCenter/ServiceCenter.java deleted file mode 100644 index 1b2c02e..0000000 --- a/version1/src/main/java/part3/Client/serviceCenter/ServiceCenter.java +++ /dev/null @@ -1,14 +0,0 @@ -package part3.Client.serviceCenter; - -import java.net.InetSocketAddress; - -/** - * @author wxx - * @version 1.0 - * @create 2024/5/3 21:42 - */ -//服务中心接口 -public interface ServiceCenter { - // 查询:根据服务名查找地址 - InetSocketAddress serviceDiscovery(String serviceName); -} diff --git a/version1/src/main/java/part3/Client/serviceCenter/ZKServiceCenter.java b/version1/src/main/java/part3/Client/serviceCenter/ZKServiceCenter.java deleted file mode 100644 index a23ff1c..0000000 --- a/version1/src/main/java/part3/Client/serviceCenter/ZKServiceCenter.java +++ /dev/null @@ -1,59 +0,0 @@ -package part3.Client.serviceCenter; - -import org.apache.curator.RetryPolicy; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.retry.ExponentialBackoffRetry; - -import java.net.InetSocketAddress; -import java.util.List; - -/** - * @author wxx - * @version 1.0 - * @create 2024/5/3 21:41 - */ -public class ZKServiceCenter implements ServiceCenter{ - // curator 提供的zookeeper客户端 - private CuratorFramework client; - //zookeeper根路径节点 - private static final String ROOT_PATH = "MyRPC"; - - //负责zookeeper客户端的初始化,并与zookeeper服务端进行连接 - public ZKServiceCenter(){ - // 指数时间重试 - RetryPolicy policy = new ExponentialBackoffRetry(1000, 3); - // zookeeper的地址固定,不管是服务提供者还是,消费者都要与之建立连接 - // sessionTimeoutMs 与 zoo.cfg中的tickTime 有关系, - // zk还会根据minSessionTimeout与maxSessionTimeout两个参数重新调整最后的超时值。默认分别为tickTime 的2倍和20倍 - // 使用心跳监听状态 - this.client = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181") - .sessionTimeoutMs(40000).retryPolicy(policy).namespace(ROOT_PATH).build(); - this.client.start(); - System.out.println("zookeeper 连接成功"); - } - //根据服务名(接口名)返回地址 - @Override - public InetSocketAddress serviceDiscovery(String serviceName) { - try { - List strings = client.getChildren().forPath("/" + serviceName); - // 这里默认用的第一个,后面加负载均衡 - String string = strings.get(0); - return parseAddress(string); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - // 地址 -> XXX.XXX.XXX.XXX:port 字符串 - private String getServiceAddress(InetSocketAddress serverAddress) { - return serverAddress.getHostName() + - ":" + - serverAddress.getPort(); - } - // 字符串解析为地址 - private InetSocketAddress parseAddress(String address) { - String[] result = address.split(":"); - return new InetSocketAddress(result[0], Integer.parseInt(result[1])); - } -} diff --git a/version1/src/main/java/part3/Server/TestServer.java b/version1/src/main/java/part3/Server/TestServer.java deleted file mode 100644 index 28f7ffd..0000000 --- a/version1/src/main/java/part3/Server/TestServer.java +++ /dev/null @@ -1,28 +0,0 @@ -package part3.Server; - - -import lombok.extern.slf4j.Slf4j; -import part3.Server.server.impl.NettyRPCRPCServer; -import part3.common.service.Impl.UserServiceImpl; -import part3.common.service.UserService; -import part3.Server.provider.ServiceProvider; -import part3.Server.server.RpcServer; -import part3.Server.server.impl.SimpleRPCRPCServer; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/11 19:39 - */ - -public class TestServer { - public static void main(String[] args) { - UserService userService=new UserServiceImpl(); - - ServiceProvider serviceProvider=new ServiceProvider("127.0.0.1",9999); - serviceProvider.provideServiceInterface(userService); - - RpcServer rpcServer=new NettyRPCRPCServer(serviceProvider); - rpcServer.start(9999); - } -} diff --git a/version1/src/main/java/part3/Server/netty/handler/NettyRPCServerHandler.java b/version1/src/main/java/part3/Server/netty/handler/NettyRPCServerHandler.java deleted file mode 100644 index aea757f..0000000 --- a/version1/src/main/java/part3/Server/netty/handler/NettyRPCServerHandler.java +++ /dev/null @@ -1,51 +0,0 @@ -package part3.Server.netty.handler; - -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.SimpleChannelInboundHandler; -import lombok.AllArgsConstructor; -import part3.Server.provider.ServiceProvider; -import part3.common.Message.RpcRequest; -import part3.common.Message.RpcResponse; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/26 16:40 - * 因为是服务器端,我们知道接受到请求格式是RPCRequest - * Object类型也行,强制转型就行 - */ -@AllArgsConstructor -public class NettyRPCServerHandler extends SimpleChannelInboundHandler { - private ServiceProvider serviceProvider; - @Override - protected void channelRead0(ChannelHandlerContext ctx, RpcRequest request) throws Exception { - RpcResponse response = getResponse(request); - ctx.writeAndFlush(response); - ctx.close(); - } - @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { - cause.printStackTrace(); - ctx.close(); - } - private RpcResponse getResponse(RpcRequest rpcRequest){ - //得到服务名 - String interfaceName=rpcRequest.getInterfaceName(); - //得到服务端相应服务实现类 - Object service = serviceProvider.getService(interfaceName); - //反射调用方法 - Method method=null; - try { - method= service.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParamsType()); - Object invoke=method.invoke(service,rpcRequest.getParams()); - return RpcResponse.sussess(invoke); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - e.printStackTrace(); - System.out.println("方法执行错误"); - return RpcResponse.fail(); - } - } -} diff --git a/version1/src/main/java/part3/Server/netty/nettyInitializer/NettyServerInitializer.java b/version1/src/main/java/part3/Server/netty/nettyInitializer/NettyServerInitializer.java deleted file mode 100644 index aff1fdb..0000000 --- a/version1/src/main/java/part3/Server/netty/nettyInitializer/NettyServerInitializer.java +++ /dev/null @@ -1,46 +0,0 @@ -package part3.Server.netty.nettyInitializer; - - -import io.netty.channel.ChannelInitializer; -import io.netty.channel.ChannelPipeline; -import io.netty.channel.socket.SocketChannel; -import io.netty.handler.codec.LengthFieldBasedFrameDecoder; -import io.netty.handler.codec.LengthFieldPrepender; -import io.netty.handler.codec.serialization.ClassResolver; -import io.netty.handler.codec.serialization.ObjectDecoder; -import io.netty.handler.codec.serialization.ObjectEncoder; -import lombok.AllArgsConstructor; -import part3.Server.provider.ServiceProvider; -import part3.Server.netty.handler.NettyRPCServerHandler; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/26 16:15 - */ -@AllArgsConstructor -public class NettyServerInitializer extends ChannelInitializer { - private ServiceProvider serviceProvider; - @Override - protected void initChannel(SocketChannel ch) throws Exception { - ChannelPipeline pipeline = ch.pipeline(); - //消息格式 【长度】【消息体】,解决沾包问题 - pipeline.addLast( - new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0,4,0,4)); - //计算当前待发送消息的长度,写入到前4个字节中 - pipeline.addLast(new LengthFieldPrepender(4)); - - //使用Java序列化方式,netty的自带的解码编码支持传输这种结构 - pipeline.addLast(new ObjectEncoder()); - //使用了Netty中的ObjectDecoder,它用于将字节流解码为 Java 对象。 - //在ObjectDecoder的构造函数中传入了一个ClassResolver 对象,用于解析类名并加载相应的类。 - pipeline.addLast(new ObjectDecoder(new ClassResolver() { - @Override - public Class resolve(String className) throws ClassNotFoundException { - return Class.forName(className); - } - })); - - pipeline.addLast(new NettyRPCServerHandler(serviceProvider)); - } -} diff --git a/version1/src/main/java/part3/Server/provider/ServiceProvider.java b/version1/src/main/java/part3/Server/provider/ServiceProvider.java deleted file mode 100644 index fa39e0a..0000000 --- a/version1/src/main/java/part3/Server/provider/ServiceProvider.java +++ /dev/null @@ -1,47 +0,0 @@ -package part3.Server.provider; - -import part3.Server.serviceRegister.ServiceRegister; -import part3.Server.serviceRegister.impl.ZKServiceRegister; - -import java.net.InetSocketAddress; -import java.util.HashMap; -import java.util.Map; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/16 17:35 - */ -public class ServiceProvider { - private Map interfaceProvider; - - private int port; - private String host; - //注册服务类 - private ServiceRegister serviceRegister; - - public ServiceProvider(String host,int port){ - //需要传入服务端自身的网络地址 - this.host=host; - this.port=port; - this.interfaceProvider=new HashMap<>(); - this.serviceRegister=new ZKServiceRegister(); - } - - public void provideServiceInterface(Object service){ - String serviceName=service.getClass().getName(); - Class[] interfaceName=service.getClass().getInterfaces(); - - for (Class clazz:interfaceName){ - //本机的映射表 - interfaceProvider.put(clazz.getName(),service); - //在注册中心注册服务 - serviceRegister.register(clazz.getName(),new InetSocketAddress(host,port)); - } - } - - public Object getService(String interfaceName){ - return interfaceProvider.get(interfaceName); - } - -} diff --git a/version1/src/main/java/part3/Server/server/RpcServer.java b/version1/src/main/java/part3/Server/server/RpcServer.java deleted file mode 100644 index d0a0fa5..0000000 --- a/version1/src/main/java/part3/Server/server/RpcServer.java +++ /dev/null @@ -1,11 +0,0 @@ -package part3.Server.server; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/12 11:26 - */ -public interface RpcServer { - void start(int port); - void stop(); -} diff --git a/version1/src/main/java/part3/Server/server/impl/NettyRPCRPCServer.java b/version1/src/main/java/part3/Server/server/impl/NettyRPCRPCServer.java deleted file mode 100644 index 2e4a34b..0000000 --- a/version1/src/main/java/part3/Server/server/impl/NettyRPCRPCServer.java +++ /dev/null @@ -1,48 +0,0 @@ -package part3.Server.server.impl; - -import io.netty.bootstrap.ServerBootstrap; -import io.netty.channel.ChannelFuture; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.nio.NioServerSocketChannel; -import lombok.AllArgsConstructor; -import part3.Server.netty.nettyInitializer.NettyServerInitializer; -import part3.Server.provider.ServiceProvider; -import part3.Server.server.RpcServer; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/26 14:01 - */ -@AllArgsConstructor -public class NettyRPCRPCServer implements RpcServer { - private ServiceProvider serviceProvider; - @Override - public void start(int port) { - // netty 服务线程组boss负责建立连接, work负责具体的请求 - NioEventLoopGroup bossGroup = new NioEventLoopGroup(); - NioEventLoopGroup workGroup = new NioEventLoopGroup(); - System.out.println("netty服务端启动了"); - try { - //启动netty服务器 - ServerBootstrap serverBootstrap = new ServerBootstrap(); - //初始化 - serverBootstrap.group(bossGroup,workGroup).channel(NioServerSocketChannel.class) - .childHandler(new NettyServerInitializer(serviceProvider)); - //同步堵塞 - ChannelFuture channelFuture=serverBootstrap.bind(port).sync(); - //死循环监听 - channelFuture.channel().closeFuture().sync(); - }catch (InterruptedException e){ - e.printStackTrace(); - }finally { - bossGroup.shutdownGracefully(); - workGroup.shutdownGracefully(); - } - } - - @Override - public void stop() { - - } -} diff --git a/version1/src/main/java/part3/Server/server/impl/SimpleRPCRPCServer.java b/version1/src/main/java/part3/Server/server/impl/SimpleRPCRPCServer.java deleted file mode 100644 index f77262a..0000000 --- a/version1/src/main/java/part3/Server/server/impl/SimpleRPCRPCServer.java +++ /dev/null @@ -1,39 +0,0 @@ -package part3.Server.server.impl; - - -import lombok.AllArgsConstructor; -import part3.Server.provider.ServiceProvider; -import part3.Server.server.RpcServer; -import part3.Server.server.work.WorkThread; - -import java.io.IOException; -import java.net.ServerSocket; -import java.net.Socket; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/12 11:37 - */ -@AllArgsConstructor -public class SimpleRPCRPCServer implements RpcServer { - private ServiceProvider serviceProvide; - @Override - public void start(int port) { - try { - ServerSocket serverSocket=new ServerSocket(port); - System.out.println("服务器启动了"); - while (true) { - Socket socket = serverSocket.accept(); - new Thread(new WorkThread(socket,serviceProvide)).start(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Override - public void stop() { - - } -} diff --git a/version1/src/main/java/part3/Server/server/work/WorkThread.java b/version1/src/main/java/part3/Server/server/work/WorkThread.java deleted file mode 100644 index 32eb732..0000000 --- a/version1/src/main/java/part3/Server/server/work/WorkThread.java +++ /dev/null @@ -1,58 +0,0 @@ -package part3.Server.server.work; - - -import lombok.AllArgsConstructor; -import part3.common.Message.RpcRequest; -import part3.common.Message.RpcResponse; -import part3.Server.provider.ServiceProvider; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.Socket; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/14 17:39 - */ -@AllArgsConstructor -public class WorkThread implements Runnable{ - private Socket socket; - private ServiceProvider serviceProvide; - @Override - public void run() { - try { - ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream()); - ObjectInputStream ois=new ObjectInputStream(socket.getInputStream()); - //读取客户端传过来的request - RpcRequest rpcRequest = (RpcRequest) ois.readObject(); - //反射调用服务方法获取返回值 - RpcResponse rpcResponse=getResponse(rpcRequest); - //向客户端写入response - oos.writeObject(rpcResponse); - oos.flush(); - } catch (IOException | ClassNotFoundException e) { - e.printStackTrace(); - } - } - private RpcResponse getResponse(RpcRequest rpcRequest){ - //得到服务名 - String interfaceName=rpcRequest.getInterfaceName(); - //得到服务端相应服务实现类 - Object service = serviceProvide.getService(interfaceName); - //反射调用方法 - Method method=null; - try { - method= service.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParamsType()); - Object invoke=method.invoke(service,rpcRequest.getParams()); - return RpcResponse.sussess(invoke); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - e.printStackTrace(); - System.out.println("方法执行错误"); - return RpcResponse.fail(); - } - } -} diff --git a/version1/src/main/java/part3/Server/serviceRegister/ServiceRegister.java b/version1/src/main/java/part3/Server/serviceRegister/ServiceRegister.java deleted file mode 100644 index 65c5be3..0000000 --- a/version1/src/main/java/part3/Server/serviceRegister/ServiceRegister.java +++ /dev/null @@ -1,15 +0,0 @@ -package part3.Server.serviceRegister; - -import java.net.InetSocketAddress; - -/** - * @author wxx - * @version 1.0 - * @create 2024/5/3 16:58 - */ -// 服务注册接口 -public interface ServiceRegister { - // 注册:保存服务与地址。 - void register(String serviceName, InetSocketAddress serviceAddress); - -} diff --git a/version1/src/main/java/part3/Server/serviceRegister/impl/ZKServiceRegister.java b/version1/src/main/java/part3/Server/serviceRegister/impl/ZKServiceRegister.java deleted file mode 100644 index 9fe332a..0000000 --- a/version1/src/main/java/part3/Server/serviceRegister/impl/ZKServiceRegister.java +++ /dev/null @@ -1,62 +0,0 @@ -package part3.Server.serviceRegister.impl; - -import org.apache.curator.RetryPolicy; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.retry.ExponentialBackoffRetry; -import org.apache.zookeeper.CreateMode; -import part3.Server.serviceRegister.ServiceRegister; - -import java.net.InetSocketAddress; -/** - * @author wxx - * @version 1.0 - * @create 2024/5/3 17:28 - */ -public class ZKServiceRegister implements ServiceRegister { - // curator 提供的zookeeper客户端 - private CuratorFramework client; - //zookeeper根路径节点 - private static final String ROOT_PATH = "MyRPC"; - - //负责zookeeper客户端的初始化,并与zookeeper服务端进行连接 - public ZKServiceRegister(){ - // 指数时间重试 - RetryPolicy policy = new ExponentialBackoffRetry(1000, 3); - // zookeeper的地址固定,不管是服务提供者还是,消费者都要与之建立连接 - // sessionTimeoutMs 与 zoo.cfg中的tickTime 有关系, - // zk还会根据minSessionTimeout与maxSessionTimeout两个参数重新调整最后的超时值。默认分别为tickTime 的2倍和20倍 - // 使用心跳监听状态 - this.client = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181") - .sessionTimeoutMs(40000).retryPolicy(policy).namespace(ROOT_PATH).build(); - this.client.start(); - System.out.println("zookeeper 连接成功"); - } - //注册服务到注册中心 - @Override - public void register(String serviceName, InetSocketAddress serviceAddress) { - try { - // serviceName创建成永久节点,服务提供者下线时,不删服务名,只删地址 - if(client.checkExists().forPath("/" + serviceName) == null){ - client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/" + serviceName); - } - // 路径地址,一个/代表一个节点 - String path = "/" + serviceName +"/"+ getServiceAddress(serviceAddress); - // 临时节点,服务器下线就删除节点 - client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path); - } catch (Exception e) { - System.out.println("此服务已存在"); - } - } - // 地址 -> XXX.XXX.XXX.XXX:port 字符串 - private String getServiceAddress(InetSocketAddress serverAddress) { - return serverAddress.getHostName() + - ":" + - serverAddress.getPort(); - } - // 字符串解析为地址 - private InetSocketAddress parseAddress(String address) { - String[] result = address.split(":"); - return new InetSocketAddress(result[0], Integer.parseInt(result[1])); - } -} diff --git a/version1/src/main/java/part3/common/Message/RpcRequest.java b/version1/src/main/java/part3/common/Message/RpcRequest.java deleted file mode 100644 index 63ba31f..0000000 --- a/version1/src/main/java/part3/common/Message/RpcRequest.java +++ /dev/null @@ -1,25 +0,0 @@ -package part3.common.Message; - -import lombok.Builder; -import lombok.Data; - -import java.io.Serializable; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/1 18:30 - * 定义发送的消息格式 - */ -@Data -@Builder -public class RpcRequest implements Serializable { - //服务类名,客户端只知道接口 - private String interfaceName; - //调用的方法名 - private String methodName; - //参数列表 - private Object[] params; - //参数类型 - private Class[] paramsType; -} diff --git a/version1/src/main/java/part3/common/Message/RpcResponse.java b/version1/src/main/java/part3/common/Message/RpcResponse.java deleted file mode 100644 index 537b630..0000000 --- a/version1/src/main/java/part3/common/Message/RpcResponse.java +++ /dev/null @@ -1,29 +0,0 @@ -package part3.common.Message; - -import lombok.Builder; -import lombok.Data; - -import java.io.Serializable; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/1 19:18 - */ -@Data -@Builder -public class RpcResponse implements Serializable { - //状态信息 - private int code; - private String message; - //具体数据 - private Object data; - - public static RpcResponse sussess(Object data){ - return RpcResponse.builder().code(200).data(data).build(); - } - public static RpcResponse fail(){ - return RpcResponse.builder().code(500).message("服务器发生错误").build(); - } -} - diff --git a/version1/src/main/java/part3/common/service/Impl/UserServiceImpl.java b/version1/src/main/java/part3/common/service/Impl/UserServiceImpl.java deleted file mode 100644 index 6fc44b2..0000000 --- a/version1/src/main/java/part3/common/service/Impl/UserServiceImpl.java +++ /dev/null @@ -1,32 +0,0 @@ -package part3.common.service.Impl; - - -import part3.common.pojo.User; -import part3.common.service.UserService; - -import java.util.Random; -import java.util.UUID; - -/** - * @author wxx - * @version 1.0 - * @create 2024/1/28 16:28 - */ -public class UserServiceImpl implements UserService { - @Override - public User getUserByUserId(Integer id) { - System.out.println("客户端查询了"+id+"的用户"); - // 模拟从数据库中取用户的行为 - Random random = new Random(); - User user = User.builder().userName(UUID.randomUUID().toString()) - .id(id) - .sex(random.nextBoolean()).build(); - return user; - } - - @Override - public Integer insertUserId(User user) { - System.out.println("插入数据成功"+user.getUserName()); - return user.getId(); - } -} \ No newline at end of file diff --git a/version1/src/main/java/part3/common/service/UserService.java b/version1/src/main/java/part3/common/service/UserService.java deleted file mode 100644 index 07efce0..0000000 --- a/version1/src/main/java/part3/common/service/UserService.java +++ /dev/null @@ -1,16 +0,0 @@ -package part3.common.service; - - -import part3.common.pojo.User; - -/** - * @author wxx - * @version 1.0 - * @create 2024/1/28 16:27 - */ -public interface UserService { - // 客户端通过这个接口调用服务端的实现类 - User getUserByUserId(Integer id); - //新增一个功能 - Integer insertUserId(User user); -} diff --git a/version1/target/classes/log4j.properties b/version1/target/classes/log4j.properties deleted file mode 100644 index 4e012fe..0000000 --- a/version1/target/classes/log4j.properties +++ /dev/null @@ -1,8 +0,0 @@ -log4j.rootLogger=ERROR, stdout -log4j.appender.stdout=org.apache.log4j.ConsoleAppender - -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n -log4j.appender.logfile=org.apache.log4j.FileAppender -log4j.appender.logfile.File=target/spring.log log4j.appender.logfile.layout=org.apache.log4j.PatternLayout -log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n diff --git a/version1/target/classes/part1/Client/IOClient.class b/version1/target/classes/part1/Client/IOClient.class deleted file mode 100644 index 3887808..0000000 Binary files a/version1/target/classes/part1/Client/IOClient.class and /dev/null differ diff --git a/version1/target/classes/part1/Client/TestClient.class b/version1/target/classes/part1/Client/TestClient.class deleted file mode 100644 index 0ccacd2..0000000 Binary files a/version1/target/classes/part1/Client/TestClient.class and /dev/null differ diff --git a/version1/target/classes/part1/Client/proxy/ClientProxy.class b/version1/target/classes/part1/Client/proxy/ClientProxy.class deleted file mode 100644 index 494800e..0000000 Binary files a/version1/target/classes/part1/Client/proxy/ClientProxy.class and /dev/null differ diff --git a/version1/target/classes/part1/Server/TestServer.class b/version1/target/classes/part1/Server/TestServer.class deleted file mode 100644 index f5eeb9c..0000000 Binary files a/version1/target/classes/part1/Server/TestServer.class and /dev/null differ diff --git a/version1/target/classes/part1/Server/provider/ServiceProvider.class b/version1/target/classes/part1/Server/provider/ServiceProvider.class deleted file mode 100644 index c99abe0..0000000 Binary files a/version1/target/classes/part1/Server/provider/ServiceProvider.class and /dev/null differ diff --git a/version1/target/classes/part1/Server/server/RpcServer.class b/version1/target/classes/part1/Server/server/RpcServer.class deleted file mode 100644 index 50b6f39..0000000 Binary files a/version1/target/classes/part1/Server/server/RpcServer.class and /dev/null differ diff --git a/version1/target/classes/part1/Server/server/impl/SimpleRPCRPCServer.class b/version1/target/classes/part1/Server/server/impl/SimpleRPCRPCServer.class deleted file mode 100644 index 561ea06..0000000 Binary files a/version1/target/classes/part1/Server/server/impl/SimpleRPCRPCServer.class and /dev/null differ diff --git a/version1/target/classes/part1/Server/server/impl/ThreadPoolRPCRPCServer.class b/version1/target/classes/part1/Server/server/impl/ThreadPoolRPCRPCServer.class deleted file mode 100644 index 29a7d90..0000000 Binary files a/version1/target/classes/part1/Server/server/impl/ThreadPoolRPCRPCServer.class and /dev/null differ diff --git a/version1/target/classes/part1/common/Message/RpcRequest$RpcRequestBuilder.class b/version1/target/classes/part1/common/Message/RpcRequest$RpcRequestBuilder.class deleted file mode 100644 index e74801c..0000000 Binary files a/version1/target/classes/part1/common/Message/RpcRequest$RpcRequestBuilder.class and /dev/null differ diff --git a/version1/target/classes/part1/common/Message/RpcRequest.class b/version1/target/classes/part1/common/Message/RpcRequest.class deleted file mode 100644 index 681fc3d..0000000 Binary files a/version1/target/classes/part1/common/Message/RpcRequest.class and /dev/null differ diff --git a/version1/target/classes/part1/common/Message/RpcResponse$RpcResponseBuilder.class b/version1/target/classes/part1/common/Message/RpcResponse$RpcResponseBuilder.class deleted file mode 100644 index 5944e04..0000000 Binary files a/version1/target/classes/part1/common/Message/RpcResponse$RpcResponseBuilder.class and /dev/null differ diff --git a/version1/target/classes/part1/common/Message/RpcResponse.class b/version1/target/classes/part1/common/Message/RpcResponse.class deleted file mode 100644 index 1176cbb..0000000 Binary files a/version1/target/classes/part1/common/Message/RpcResponse.class and /dev/null differ diff --git a/version1/target/classes/part1/common/pojo/User$UserBuilder.class b/version1/target/classes/part1/common/pojo/User$UserBuilder.class deleted file mode 100644 index 4dad3e5..0000000 Binary files a/version1/target/classes/part1/common/pojo/User$UserBuilder.class and /dev/null differ diff --git a/version1/target/classes/part1/common/pojo/User.class b/version1/target/classes/part1/common/pojo/User.class deleted file mode 100644 index 5639736..0000000 Binary files a/version1/target/classes/part1/common/pojo/User.class and /dev/null differ diff --git a/version1/target/classes/part1/common/service/Impl/UserServiceImpl.class b/version1/target/classes/part1/common/service/Impl/UserServiceImpl.class deleted file mode 100644 index 4f66e73..0000000 Binary files a/version1/target/classes/part1/common/service/Impl/UserServiceImpl.class and /dev/null differ diff --git a/version1/target/classes/part1/common/service/UserService.class b/version1/target/classes/part1/common/service/UserService.class deleted file mode 100644 index 216f6e4..0000000 Binary files a/version1/target/classes/part1/common/service/UserService.class and /dev/null differ diff --git a/version1/target/classes/part2/Client/IOClient.class b/version1/target/classes/part2/Client/IOClient.class deleted file mode 100644 index 56de353..0000000 Binary files a/version1/target/classes/part2/Client/IOClient.class and /dev/null differ diff --git a/version1/target/classes/part2/Client/TestClient.class b/version1/target/classes/part2/Client/TestClient.class deleted file mode 100644 index 9dae865..0000000 Binary files a/version1/target/classes/part2/Client/TestClient.class and /dev/null differ diff --git a/version1/target/classes/part2/Client/netty/handler/NettyClientHandler.class b/version1/target/classes/part2/Client/netty/handler/NettyClientHandler.class deleted file mode 100644 index 1f6f7ec..0000000 Binary files a/version1/target/classes/part2/Client/netty/handler/NettyClientHandler.class and /dev/null differ diff --git a/version1/target/classes/part2/Client/netty/nettyInitializer/NettyClientInitializer$1.class b/version1/target/classes/part2/Client/netty/nettyInitializer/NettyClientInitializer$1.class deleted file mode 100644 index 9999e18..0000000 Binary files a/version1/target/classes/part2/Client/netty/nettyInitializer/NettyClientInitializer$1.class and /dev/null differ diff --git a/version1/target/classes/part2/Client/netty/nettyInitializer/NettyClientInitializer.class b/version1/target/classes/part2/Client/netty/nettyInitializer/NettyClientInitializer.class deleted file mode 100644 index 9f22eb6..0000000 Binary files a/version1/target/classes/part2/Client/netty/nettyInitializer/NettyClientInitializer.class and /dev/null differ diff --git a/version1/target/classes/part2/Client/proxy/ClientProxy.class b/version1/target/classes/part2/Client/proxy/ClientProxy.class deleted file mode 100644 index 994803e..0000000 Binary files a/version1/target/classes/part2/Client/proxy/ClientProxy.class and /dev/null differ diff --git a/version1/target/classes/part2/Client/rpcClient/RpcClient.class b/version1/target/classes/part2/Client/rpcClient/RpcClient.class deleted file mode 100644 index 0038bab..0000000 Binary files a/version1/target/classes/part2/Client/rpcClient/RpcClient.class and /dev/null differ diff --git a/version1/target/classes/part2/Client/rpcClient/impl/NettyRpcClient.class b/version1/target/classes/part2/Client/rpcClient/impl/NettyRpcClient.class deleted file mode 100644 index 4192d71..0000000 Binary files a/version1/target/classes/part2/Client/rpcClient/impl/NettyRpcClient.class and /dev/null differ diff --git a/version1/target/classes/part2/Client/rpcClient/impl/SimpleSocketRpcCilent.class b/version1/target/classes/part2/Client/rpcClient/impl/SimpleSocketRpcCilent.class deleted file mode 100644 index 84f7e0d..0000000 Binary files a/version1/target/classes/part2/Client/rpcClient/impl/SimpleSocketRpcCilent.class and /dev/null differ diff --git a/version1/target/classes/part2/Server/TestServer.class b/version1/target/classes/part2/Server/TestServer.class deleted file mode 100644 index 1206f91..0000000 Binary files a/version1/target/classes/part2/Server/TestServer.class and /dev/null differ diff --git a/version1/target/classes/part2/Server/netty/handler/NettyRPCServerHandler.class b/version1/target/classes/part2/Server/netty/handler/NettyRPCServerHandler.class deleted file mode 100644 index 465acff..0000000 Binary files a/version1/target/classes/part2/Server/netty/handler/NettyRPCServerHandler.class and /dev/null differ diff --git a/version1/target/classes/part2/Server/netty/nettyInitializer/NettyServerInitializer$1.class b/version1/target/classes/part2/Server/netty/nettyInitializer/NettyServerInitializer$1.class deleted file mode 100644 index 9fc3255..0000000 Binary files a/version1/target/classes/part2/Server/netty/nettyInitializer/NettyServerInitializer$1.class and /dev/null differ diff --git a/version1/target/classes/part2/Server/netty/nettyInitializer/NettyServerInitializer.class b/version1/target/classes/part2/Server/netty/nettyInitializer/NettyServerInitializer.class deleted file mode 100644 index 7527f69..0000000 Binary files a/version1/target/classes/part2/Server/netty/nettyInitializer/NettyServerInitializer.class and /dev/null differ diff --git a/version1/target/classes/part2/Server/provider/ServiceProvider.class b/version1/target/classes/part2/Server/provider/ServiceProvider.class deleted file mode 100644 index 2e22d58..0000000 Binary files a/version1/target/classes/part2/Server/provider/ServiceProvider.class and /dev/null differ diff --git a/version1/target/classes/part2/Server/server/RpcServer.class b/version1/target/classes/part2/Server/server/RpcServer.class deleted file mode 100644 index c503b94..0000000 Binary files a/version1/target/classes/part2/Server/server/RpcServer.class and /dev/null differ diff --git a/version1/target/classes/part2/Server/server/impl/NettyRPCRPCServer.class b/version1/target/classes/part2/Server/server/impl/NettyRPCRPCServer.class deleted file mode 100644 index c3d4155..0000000 Binary files a/version1/target/classes/part2/Server/server/impl/NettyRPCRPCServer.class and /dev/null differ diff --git a/version1/target/classes/part2/Server/server/impl/SimpleRPCRPCServer.class b/version1/target/classes/part2/Server/server/impl/SimpleRPCRPCServer.class deleted file mode 100644 index 8c1adcc..0000000 Binary files a/version1/target/classes/part2/Server/server/impl/SimpleRPCRPCServer.class and /dev/null differ diff --git a/version1/target/classes/part2/Server/server/impl/ThreadPoolRPCRPCServer.class b/version1/target/classes/part2/Server/server/impl/ThreadPoolRPCRPCServer.class deleted file mode 100644 index 3ef15ef..0000000 Binary files a/version1/target/classes/part2/Server/server/impl/ThreadPoolRPCRPCServer.class and /dev/null differ diff --git a/version1/target/classes/part2/Server/server/work/WorkThread.class b/version1/target/classes/part2/Server/server/work/WorkThread.class deleted file mode 100644 index 99c3e6c..0000000 Binary files a/version1/target/classes/part2/Server/server/work/WorkThread.class and /dev/null differ diff --git a/version1/target/classes/part2/common/Message/RpcRequest$RpcRequestBuilder.class b/version1/target/classes/part2/common/Message/RpcRequest$RpcRequestBuilder.class deleted file mode 100644 index fbc702b..0000000 Binary files a/version1/target/classes/part2/common/Message/RpcRequest$RpcRequestBuilder.class and /dev/null differ diff --git a/version1/target/classes/part2/common/Message/RpcRequest.class b/version1/target/classes/part2/common/Message/RpcRequest.class deleted file mode 100644 index cb983fd..0000000 Binary files a/version1/target/classes/part2/common/Message/RpcRequest.class and /dev/null differ diff --git a/version1/target/classes/part2/common/Message/RpcResponse$RpcResponseBuilder.class b/version1/target/classes/part2/common/Message/RpcResponse$RpcResponseBuilder.class deleted file mode 100644 index eaa4c05..0000000 Binary files a/version1/target/classes/part2/common/Message/RpcResponse$RpcResponseBuilder.class and /dev/null differ diff --git a/version1/target/classes/part2/common/Message/RpcResponse.class b/version1/target/classes/part2/common/Message/RpcResponse.class deleted file mode 100644 index 33f74ff..0000000 Binary files a/version1/target/classes/part2/common/Message/RpcResponse.class and /dev/null differ diff --git a/version1/target/classes/part2/common/pojo/User$UserBuilder.class b/version1/target/classes/part2/common/pojo/User$UserBuilder.class deleted file mode 100644 index 76e3c45..0000000 Binary files a/version1/target/classes/part2/common/pojo/User$UserBuilder.class and /dev/null differ diff --git a/version1/target/classes/part2/common/pojo/User.class b/version1/target/classes/part2/common/pojo/User.class deleted file mode 100644 index c59ad76..0000000 Binary files a/version1/target/classes/part2/common/pojo/User.class and /dev/null differ diff --git a/version1/target/classes/part2/common/service/Impl/UserServiceImpl.class b/version1/target/classes/part2/common/service/Impl/UserServiceImpl.class deleted file mode 100644 index 9ed2ee7..0000000 Binary files a/version1/target/classes/part2/common/service/Impl/UserServiceImpl.class and /dev/null differ diff --git a/version1/target/classes/part2/common/service/UserService.class b/version1/target/classes/part2/common/service/UserService.class deleted file mode 100644 index 51f12d3..0000000 Binary files a/version1/target/classes/part2/common/service/UserService.class and /dev/null differ diff --git a/version1/target/classes/part3/Client/TestClient.class b/version1/target/classes/part3/Client/TestClient.class deleted file mode 100644 index 7e27342..0000000 Binary files a/version1/target/classes/part3/Client/TestClient.class and /dev/null differ diff --git a/version1/target/classes/part3/Client/netty/handler/NettyClientHandler.class b/version1/target/classes/part3/Client/netty/handler/NettyClientHandler.class deleted file mode 100644 index 4d07169..0000000 Binary files a/version1/target/classes/part3/Client/netty/handler/NettyClientHandler.class and /dev/null differ diff --git a/version1/target/classes/part3/Client/netty/nettyInitializer/NettyClientInitializer$1.class b/version1/target/classes/part3/Client/netty/nettyInitializer/NettyClientInitializer$1.class deleted file mode 100644 index 15ceae6..0000000 Binary files a/version1/target/classes/part3/Client/netty/nettyInitializer/NettyClientInitializer$1.class and /dev/null differ diff --git a/version1/target/classes/part3/Client/netty/nettyInitializer/NettyClientInitializer.class b/version1/target/classes/part3/Client/netty/nettyInitializer/NettyClientInitializer.class deleted file mode 100644 index 322f0e7..0000000 Binary files a/version1/target/classes/part3/Client/netty/nettyInitializer/NettyClientInitializer.class and /dev/null differ diff --git a/version1/target/classes/part3/Client/proxy/ClientProxy.class b/version1/target/classes/part3/Client/proxy/ClientProxy.class deleted file mode 100644 index 9175c23..0000000 Binary files a/version1/target/classes/part3/Client/proxy/ClientProxy.class and /dev/null differ diff --git a/version1/target/classes/part3/Client/rpcClient/RpcClient.class b/version1/target/classes/part3/Client/rpcClient/RpcClient.class deleted file mode 100644 index 5a806b0..0000000 Binary files a/version1/target/classes/part3/Client/rpcClient/RpcClient.class and /dev/null differ diff --git a/version1/target/classes/part3/Client/rpcClient/impl/NettyRpcClient.class b/version1/target/classes/part3/Client/rpcClient/impl/NettyRpcClient.class deleted file mode 100644 index ff59289..0000000 Binary files a/version1/target/classes/part3/Client/rpcClient/impl/NettyRpcClient.class and /dev/null differ diff --git a/version1/target/classes/part3/Client/rpcClient/impl/SimpleSocketRpcCilent.class b/version1/target/classes/part3/Client/rpcClient/impl/SimpleSocketRpcCilent.class deleted file mode 100644 index 3307eeb..0000000 Binary files a/version1/target/classes/part3/Client/rpcClient/impl/SimpleSocketRpcCilent.class and /dev/null differ diff --git a/version1/target/classes/part3/Client/serviceCenter/ServiceCenter.class b/version1/target/classes/part3/Client/serviceCenter/ServiceCenter.class deleted file mode 100644 index 0cace88..0000000 Binary files a/version1/target/classes/part3/Client/serviceCenter/ServiceCenter.class and /dev/null differ diff --git a/version1/target/classes/part3/Client/serviceCenter/ZKServiceCenter.class b/version1/target/classes/part3/Client/serviceCenter/ZKServiceCenter.class deleted file mode 100644 index 69e72bb..0000000 Binary files a/version1/target/classes/part3/Client/serviceCenter/ZKServiceCenter.class and /dev/null differ diff --git a/version1/target/classes/part3/Server/TestServer.class b/version1/target/classes/part3/Server/TestServer.class deleted file mode 100644 index 9901b75..0000000 Binary files a/version1/target/classes/part3/Server/TestServer.class and /dev/null differ diff --git a/version1/target/classes/part3/Server/netty/handler/NettyRPCServerHandler.class b/version1/target/classes/part3/Server/netty/handler/NettyRPCServerHandler.class deleted file mode 100644 index 2d7b34d..0000000 Binary files a/version1/target/classes/part3/Server/netty/handler/NettyRPCServerHandler.class and /dev/null differ diff --git a/version1/target/classes/part3/Server/netty/nettyInitializer/NettyServerInitializer$1.class b/version1/target/classes/part3/Server/netty/nettyInitializer/NettyServerInitializer$1.class deleted file mode 100644 index 35a2e4a..0000000 Binary files a/version1/target/classes/part3/Server/netty/nettyInitializer/NettyServerInitializer$1.class and /dev/null differ diff --git a/version1/target/classes/part3/Server/netty/nettyInitializer/NettyServerInitializer.class b/version1/target/classes/part3/Server/netty/nettyInitializer/NettyServerInitializer.class deleted file mode 100644 index f6d5010..0000000 Binary files a/version1/target/classes/part3/Server/netty/nettyInitializer/NettyServerInitializer.class and /dev/null differ diff --git a/version1/target/classes/part3/Server/provider/ServiceProvider.class b/version1/target/classes/part3/Server/provider/ServiceProvider.class deleted file mode 100644 index de60431..0000000 Binary files a/version1/target/classes/part3/Server/provider/ServiceProvider.class and /dev/null differ diff --git a/version1/target/classes/part3/Server/server/RpcServer.class b/version1/target/classes/part3/Server/server/RpcServer.class deleted file mode 100644 index 7aa6e68..0000000 Binary files a/version1/target/classes/part3/Server/server/RpcServer.class and /dev/null differ diff --git a/version1/target/classes/part3/Server/server/impl/NettyRPCRPCServer.class b/version1/target/classes/part3/Server/server/impl/NettyRPCRPCServer.class deleted file mode 100644 index 4925c11..0000000 Binary files a/version1/target/classes/part3/Server/server/impl/NettyRPCRPCServer.class and /dev/null differ diff --git a/version1/target/classes/part3/Server/server/impl/SimpleRPCRPCServer.class b/version1/target/classes/part3/Server/server/impl/SimpleRPCRPCServer.class deleted file mode 100644 index bd2c8f6..0000000 Binary files a/version1/target/classes/part3/Server/server/impl/SimpleRPCRPCServer.class and /dev/null differ diff --git a/version1/target/classes/part3/Server/server/work/WorkThread.class b/version1/target/classes/part3/Server/server/work/WorkThread.class deleted file mode 100644 index 05f64e6..0000000 Binary files a/version1/target/classes/part3/Server/server/work/WorkThread.class and /dev/null differ diff --git a/version1/target/classes/part3/Server/serviceRegister/ServiceRegister.class b/version1/target/classes/part3/Server/serviceRegister/ServiceRegister.class deleted file mode 100644 index 95ca80a..0000000 Binary files a/version1/target/classes/part3/Server/serviceRegister/ServiceRegister.class and /dev/null differ diff --git a/version1/target/classes/part3/Server/serviceRegister/impl/ZKServiceRegister.class b/version1/target/classes/part3/Server/serviceRegister/impl/ZKServiceRegister.class deleted file mode 100644 index f281b3c..0000000 Binary files a/version1/target/classes/part3/Server/serviceRegister/impl/ZKServiceRegister.class and /dev/null differ diff --git a/version1/target/classes/part3/common/Message/RpcRequest$RpcRequestBuilder.class b/version1/target/classes/part3/common/Message/RpcRequest$RpcRequestBuilder.class deleted file mode 100644 index 2b9369e..0000000 Binary files a/version1/target/classes/part3/common/Message/RpcRequest$RpcRequestBuilder.class and /dev/null differ diff --git a/version1/target/classes/part3/common/Message/RpcRequest.class b/version1/target/classes/part3/common/Message/RpcRequest.class deleted file mode 100644 index 2b045ea..0000000 Binary files a/version1/target/classes/part3/common/Message/RpcRequest.class and /dev/null differ diff --git a/version1/target/classes/part3/common/Message/RpcResponse$RpcResponseBuilder.class b/version1/target/classes/part3/common/Message/RpcResponse$RpcResponseBuilder.class deleted file mode 100644 index 4108421..0000000 Binary files a/version1/target/classes/part3/common/Message/RpcResponse$RpcResponseBuilder.class and /dev/null differ diff --git a/version1/target/classes/part3/common/Message/RpcResponse.class b/version1/target/classes/part3/common/Message/RpcResponse.class deleted file mode 100644 index 3321fd0..0000000 Binary files a/version1/target/classes/part3/common/Message/RpcResponse.class and /dev/null differ diff --git a/version1/target/classes/part3/common/pojo/User$UserBuilder.class b/version1/target/classes/part3/common/pojo/User$UserBuilder.class deleted file mode 100644 index 08843db..0000000 Binary files a/version1/target/classes/part3/common/pojo/User$UserBuilder.class and /dev/null differ diff --git a/version1/target/classes/part3/common/pojo/User.class b/version1/target/classes/part3/common/pojo/User.class deleted file mode 100644 index c6480d7..0000000 Binary files a/version1/target/classes/part3/common/pojo/User.class and /dev/null differ diff --git a/version1/target/classes/part3/common/service/Impl/UserServiceImpl.class b/version1/target/classes/part3/common/service/Impl/UserServiceImpl.class deleted file mode 100644 index 1811931..0000000 Binary files a/version1/target/classes/part3/common/service/Impl/UserServiceImpl.class and /dev/null differ diff --git a/version1/target/classes/part3/common/service/UserService.class b/version1/target/classes/part3/common/service/UserService.class deleted file mode 100644 index a2e6fc6..0000000 Binary files a/version1/target/classes/part3/common/service/UserService.class and /dev/null differ diff --git a/version2/pom.xml b/version2/pom.xml deleted file mode 100644 index 4626ed3..0000000 --- a/version2/pom.xml +++ /dev/null @@ -1,54 +0,0 @@ - - - 4.0.0 - - org.example - version2 - 1.0-SNAPSHOT - - - 8 - 8 - UTF-8 - - - - org.projectlombok - lombok - 1.18.30 - compile - - - org.slf4j - slf4j-log4j12 - 1.7.25 - - - org.apache.logging.log4j - log4j-1.2-api - 2.8.2 - - - - io.netty - netty-all - 4.1.51.Final - compile - - - - org.apache.curator - curator-recipes - 5.1.0 - - - com.alibaba - fastjson - 1.2.83 - - - - - \ No newline at end of file diff --git a/version2/src/main/java/part1/Client/TestClient.java b/version2/src/main/java/part1/Client/TestClient.java deleted file mode 100644 index 6e6715c..0000000 --- a/version2/src/main/java/part1/Client/TestClient.java +++ /dev/null @@ -1,28 +0,0 @@ -package part1.Client; - - -import part1.Client.proxy.ClientProxy; -import part1.common.service.UserService; -import part1.common.pojo.User; - - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/6 18:39 - */ - -public class TestClient { - public static void main(String[] args) { - ClientProxy clientProxy=new ClientProxy(); - //ClientProxy clientProxy=new part2.Client.proxy.ClientProxy("127.0.0.1",9999,0); - UserService proxy=clientProxy.getProxy(UserService.class); - - User user = proxy.getUserByUserId(1); - System.out.println("从服务端得到的user="+user.toString()); - - User u=User.builder().id(100).userName("wxx").sex(true).build(); - Integer id = proxy.insertUserId(u); - System.out.println("向服务端插入user的id"+id); - } -} diff --git a/version2/src/main/java/part1/Client/netty/handler/NettyClientHandler.java b/version2/src/main/java/part1/Client/netty/handler/NettyClientHandler.java deleted file mode 100644 index 31858c6..0000000 --- a/version2/src/main/java/part1/Client/netty/handler/NettyClientHandler.java +++ /dev/null @@ -1,27 +0,0 @@ -package part1.Client.netty.handler; - -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.SimpleChannelInboundHandler; -import io.netty.util.AttributeKey; -import part1.common.Message.RpcResponse; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/26 17:29 - */ -public class NettyClientHandler extends SimpleChannelInboundHandler { - @Override - protected void channelRead0(ChannelHandlerContext ctx, RpcResponse response) throws Exception { - // 接收到response, 给channel设计别名,让sendRequest里读取response - AttributeKey key = AttributeKey.valueOf("RPCResponse"); - ctx.channel().attr(key).set(response); - ctx.channel().close(); - } - - @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { - cause.printStackTrace(); - ctx.close(); - } -} diff --git a/version2/src/main/java/part1/Client/netty/nettyInitializer/NettyClientInitializer.java b/version2/src/main/java/part1/Client/netty/nettyInitializer/NettyClientInitializer.java deleted file mode 100644 index 28e781f..0000000 --- a/version2/src/main/java/part1/Client/netty/nettyInitializer/NettyClientInitializer.java +++ /dev/null @@ -1,31 +0,0 @@ -package part1.Client.netty.nettyInitializer; - - -import io.netty.channel.ChannelInitializer; -import io.netty.channel.ChannelPipeline; -import io.netty.channel.socket.SocketChannel; -import io.netty.handler.codec.LengthFieldBasedFrameDecoder; -import io.netty.handler.codec.LengthFieldPrepender; -import io.netty.handler.codec.serialization.ClassResolver; -import io.netty.handler.codec.serialization.ObjectDecoder; -import io.netty.handler.codec.serialization.ObjectEncoder; -import part1.Client.netty.handler.NettyClientHandler; -import part1.common.serializer.myCode.MyDecoder; -import part1.common.serializer.myCode.MyEncoder; -import part1.common.serializer.mySerializer.JsonSerializer; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/26 17:26 - */ -public class NettyClientInitializer extends ChannelInitializer { - @Override - protected void initChannel(SocketChannel ch) throws Exception { - ChannelPipeline pipeline = ch.pipeline(); - //使用自定义的编/解码器 - pipeline.addLast(new MyDecoder()); - pipeline.addLast(new MyEncoder(new JsonSerializer())); - pipeline.addLast(new NettyClientHandler()); - } -} diff --git a/version2/src/main/java/part1/Client/proxy/ClientProxy.java b/version2/src/main/java/part1/Client/proxy/ClientProxy.java deleted file mode 100644 index c4ff57b..0000000 --- a/version2/src/main/java/part1/Client/proxy/ClientProxy.java +++ /dev/null @@ -1,42 +0,0 @@ -package part1.Client.proxy; - - -import part1.Client.rpcClient.RpcClient; -import part1.Client.rpcClient.impl.NettyRpcClient; -import part1.common.Message.RpcRequest; -import part1.common.Message.RpcResponse; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/6 16:49 - */ -public class ClientProxy implements InvocationHandler { - //传入参数service接口的class对象,反射封装成一个request - - private RpcClient rpcClient; - public ClientProxy(){ - rpcClient=new NettyRpcClient(); - } - - //jdk动态代理,每一次代理对象调用方法,都会经过此方法增强(反射获取request对象,socket发送到服务端) - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - //构建request - RpcRequest request=RpcRequest.builder() - .interfaceName(method.getDeclaringClass().getName()) - .methodName(method.getName()) - .params(args).paramsType(method.getParameterTypes()).build(); - //数据传输 - RpcResponse response= rpcClient.sendRequest(request); - return response.getData(); - } - public T getProxy(Class clazz){ - Object o = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, this); - return (T)o; - } -} diff --git a/version2/src/main/java/part1/Client/rpcClient/RpcClient.java b/version2/src/main/java/part1/Client/rpcClient/RpcClient.java deleted file mode 100644 index c665530..0000000 --- a/version2/src/main/java/part1/Client/rpcClient/RpcClient.java +++ /dev/null @@ -1,15 +0,0 @@ -package part1.Client.rpcClient; - -import part1.common.Message.RpcRequest; -import part1.common.Message.RpcResponse; - -/** - * @author wxx - * @version 1.0 - * @create 2024/5/2 18:55 - */ -public interface RpcClient { - - //定义底层通信的方法 - RpcResponse sendRequest(RpcRequest request); -} diff --git a/version2/src/main/java/part1/Client/rpcClient/impl/NettyRpcClient.java b/version2/src/main/java/part1/Client/rpcClient/impl/NettyRpcClient.java deleted file mode 100644 index 4cc425c..0000000 --- a/version2/src/main/java/part1/Client/rpcClient/impl/NettyRpcClient.java +++ /dev/null @@ -1,68 +0,0 @@ -package part1.Client.rpcClient.impl; - -import io.netty.bootstrap.Bootstrap; -import io.netty.channel.Channel; -import io.netty.channel.ChannelFuture; -import io.netty.channel.EventLoopGroup; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.nio.NioSocketChannel; -import io.netty.util.AttributeKey; -import part1.Client.rpcClient.RpcClient; -import part1.common.Message.RpcRequest; -import part1.Client.netty.nettyInitializer.NettyClientInitializer; -import part1.Client.serviceCenter.ServiceCenter; -import part1.Client.serviceCenter.ZKServiceCenter; -import part1.common.Message.RpcResponse; - -import java.net.InetSocketAddress; - -/** - * @author wxx - * @version 1.0 - * @create 2024/5/2 19:40 - */ -public class NettyRpcClient implements RpcClient { - - private static final Bootstrap bootstrap; - private static final EventLoopGroup eventLoopGroup; - - private ServiceCenter serviceCenter; - public NettyRpcClient(){ - this.serviceCenter=new ZKServiceCenter(); - } - - //netty客户端初始化 - static { - eventLoopGroup = new NioEventLoopGroup(); - bootstrap = new Bootstrap(); - bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class) - .handler(new NettyClientInitializer()); - } - @Override - public RpcResponse sendRequest(RpcRequest request) { - //从注册中心获取host,post - InetSocketAddress address = serviceCenter.serviceDiscovery(request.getInterfaceName()); - String host = address.getHostName(); - int port = address.getPort(); - try { - ChannelFuture channelFuture = bootstrap.connect(host, port).sync(); - Channel channel = channelFuture.channel(); - // 发送数据 - channel.writeAndFlush(request); - //sync()堵塞获取结果 - channel.closeFuture().sync(); - // 阻塞的获得结果,通过给channel设计别名,获取特定名字下的channel中的内容(这个在hanlder中设置) - // AttributeKey是,线程隔离的,不会由线程安全问题。 - // 当前场景下选择堵塞获取结果 - // 其它场景也可以选择添加监听器的方式来异步获取结果 channelFuture.addListener... - AttributeKey key = AttributeKey.valueOf("RPCResponse"); - RpcResponse response = channel.attr(key).get(); - - System.out.println(response); - return response; - } catch (InterruptedException e) { - e.printStackTrace(); - } - return null; - } -} diff --git a/version2/src/main/java/part1/Client/rpcClient/impl/SimpleSocketRpcCilent.java b/version2/src/main/java/part1/Client/rpcClient/impl/SimpleSocketRpcCilent.java deleted file mode 100644 index d74af41..0000000 --- a/version2/src/main/java/part1/Client/rpcClient/impl/SimpleSocketRpcCilent.java +++ /dev/null @@ -1,41 +0,0 @@ -package part1.Client.rpcClient.impl; - -import part1.Client.rpcClient.RpcClient; -import part1.common.Message.RpcRequest; -import part1.common.Message.RpcResponse; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.net.Socket; - -/** - * @author wxx - * @version 1.0 - * @create 2024/5/2 18:58 - */ -public class SimpleSocketRpcCilent implements RpcClient { - private String host; - private int port; - public SimpleSocketRpcCilent(String host,int port){ - this.host=host; - this.port=port; - } - @Override - public RpcResponse sendRequest(RpcRequest request) { - try { - Socket socket=new Socket(host, port); - ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream()); - ObjectInputStream ois=new ObjectInputStream(socket.getInputStream()); - - oos.writeObject(request); - oos.flush(); - - RpcResponse response=(RpcResponse) ois.readObject(); - return response; - } catch (IOException | ClassNotFoundException e) { - e.printStackTrace(); - return null; - } - } -} diff --git a/version2/src/main/java/part1/Client/serviceCenter/ServiceCenter.java b/version2/src/main/java/part1/Client/serviceCenter/ServiceCenter.java deleted file mode 100644 index 1842b94..0000000 --- a/version2/src/main/java/part1/Client/serviceCenter/ServiceCenter.java +++ /dev/null @@ -1,14 +0,0 @@ -package part1.Client.serviceCenter; - -import java.net.InetSocketAddress; - -/** - * @author wxx - * @version 1.0 - * @create 2024/5/3 21:42 - */ -//服务中心接口 -public interface ServiceCenter { - // 查询:根据服务名查找地址 - InetSocketAddress serviceDiscovery(String serviceName); -} diff --git a/version2/src/main/java/part1/Client/serviceCenter/ZKServiceCenter.java b/version2/src/main/java/part1/Client/serviceCenter/ZKServiceCenter.java deleted file mode 100644 index b62de1f..0000000 --- a/version2/src/main/java/part1/Client/serviceCenter/ZKServiceCenter.java +++ /dev/null @@ -1,59 +0,0 @@ -package part1.Client.serviceCenter; - -import org.apache.curator.RetryPolicy; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.retry.ExponentialBackoffRetry; - -import java.net.InetSocketAddress; -import java.util.List; - -/** - * @author wxx - * @version 1.0 - * @create 2024/5/3 21:41 - */ -public class ZKServiceCenter implements ServiceCenter{ - // curator 提供的zookeeper客户端 - private CuratorFramework client; - //zookeeper根路径节点 - private static final String ROOT_PATH = "MyRPC"; - - //负责zookeeper客户端的初始化,并与zookeeper服务端进行连接 - public ZKServiceCenter(){ - // 指数时间重试 - RetryPolicy policy = new ExponentialBackoffRetry(1000, 3); - // zookeeper的地址固定,不管是服务提供者还是,消费者都要与之建立连接 - // sessionTimeoutMs 与 zoo.cfg中的tickTime 有关系, - // zk还会根据minSessionTimeout与maxSessionTimeout两个参数重新调整最后的超时值。默认分别为tickTime 的2倍和20倍 - // 使用心跳监听状态 - this.client = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181") - .sessionTimeoutMs(40000).retryPolicy(policy).namespace(ROOT_PATH).build(); - this.client.start(); - System.out.println("zookeeper 连接成功"); - } - //根据服务名(接口名)返回地址 - @Override - public InetSocketAddress serviceDiscovery(String serviceName) { - try { - List strings = client.getChildren().forPath("/" + serviceName); - // 这里默认用的第一个,后面加负载均衡 - String string = strings.get(0); - return parseAddress(string); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - // 地址 -> XXX.XXX.XXX.XXX:port 字符串 - private String getServiceAddress(InetSocketAddress serverAddress) { - return serverAddress.getHostName() + - ":" + - serverAddress.getPort(); - } - // 字符串解析为地址 - private InetSocketAddress parseAddress(String address) { - String[] result = address.split(":"); - return new InetSocketAddress(result[0], Integer.parseInt(result[1])); - } -} diff --git a/version2/src/main/java/part1/Server/TestServer.java b/version2/src/main/java/part1/Server/TestServer.java deleted file mode 100644 index baaf058..0000000 --- a/version2/src/main/java/part1/Server/TestServer.java +++ /dev/null @@ -1,26 +0,0 @@ -package part1.Server; - - -import part1.Server.provider.ServiceProvider; -import part1.Server.server.impl.NettyRPCRPCServer; -import part1.Server.server.RpcServer; -import part1.common.service.Impl.UserServiceImpl; -import part1.common.service.UserService; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/11 19:39 - */ - -public class TestServer { - public static void main(String[] args) { - UserService userService=new UserServiceImpl(); - - ServiceProvider serviceProvider=new ServiceProvider("127.0.0.1",9999); - serviceProvider.provideServiceInterface(userService); - - RpcServer rpcServer=new NettyRPCRPCServer(serviceProvider); - rpcServer.start(9999); - } -} diff --git a/version2/src/main/java/part1/Server/netty/handler/NettyRPCServerHandler.java b/version2/src/main/java/part1/Server/netty/handler/NettyRPCServerHandler.java deleted file mode 100644 index 5b01246..0000000 --- a/version2/src/main/java/part1/Server/netty/handler/NettyRPCServerHandler.java +++ /dev/null @@ -1,51 +0,0 @@ -package part1.Server.netty.handler; - -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.SimpleChannelInboundHandler; -import lombok.AllArgsConstructor; -import part1.Server.provider.ServiceProvider; -import part1.common.Message.RpcRequest; -import part1.common.Message.RpcResponse; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/26 16:40 - * 因为是服务器端,我们知道接受到请求格式是RPCRequest - * Object类型也行,强制转型就行 - */ -@AllArgsConstructor -public class NettyRPCServerHandler extends SimpleChannelInboundHandler { - private ServiceProvider serviceProvider; - @Override - protected void channelRead0(ChannelHandlerContext ctx, RpcRequest request) throws Exception { - RpcResponse response = getResponse(request); - ctx.writeAndFlush(response); - ctx.close(); - } - @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { - cause.printStackTrace(); - ctx.close(); - } - private RpcResponse getResponse(RpcRequest rpcRequest){ - //得到服务名 - String interfaceName=rpcRequest.getInterfaceName(); - //得到服务端相应服务实现类 - Object service = serviceProvider.getService(interfaceName); - //反射调用方法 - Method method=null; - try { - method= service.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParamsType()); - Object invoke=method.invoke(service,rpcRequest.getParams()); - return RpcResponse.sussess(invoke); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - e.printStackTrace(); - System.out.println("方法执行错误"); - return RpcResponse.fail(); - } - } -} diff --git a/version2/src/main/java/part1/Server/netty/nettyInitializer/NettyServerInitializer.java b/version2/src/main/java/part1/Server/netty/nettyInitializer/NettyServerInitializer.java deleted file mode 100644 index bb7a4a1..0000000 --- a/version2/src/main/java/part1/Server/netty/nettyInitializer/NettyServerInitializer.java +++ /dev/null @@ -1,35 +0,0 @@ -package part1.Server.netty.nettyInitializer; - - -import io.netty.channel.ChannelInitializer; -import io.netty.channel.ChannelPipeline; -import io.netty.channel.socket.SocketChannel; -import io.netty.handler.codec.LengthFieldBasedFrameDecoder; -import io.netty.handler.codec.LengthFieldPrepender; -import io.netty.handler.codec.serialization.ClassResolver; -import io.netty.handler.codec.serialization.ObjectDecoder; -import io.netty.handler.codec.serialization.ObjectEncoder; -import lombok.AllArgsConstructor; -import part1.Server.netty.handler.NettyRPCServerHandler; -import part1.Server.provider.ServiceProvider; -import part1.common.serializer.myCode.MyDecoder; -import part1.common.serializer.myCode.MyEncoder; -import part1.common.serializer.mySerializer.JsonSerializer; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/26 16:15 - */ -@AllArgsConstructor -public class NettyServerInitializer extends ChannelInitializer { - private ServiceProvider serviceProvider; - @Override - protected void initChannel(SocketChannel ch) throws Exception { - ChannelPipeline pipeline = ch.pipeline(); - //使用自定义的编/解码器 - pipeline.addLast(new MyEncoder(new JsonSerializer())); - pipeline.addLast(new MyDecoder()); - pipeline.addLast(new NettyRPCServerHandler(serviceProvider)); - } -} diff --git a/version2/src/main/java/part1/Server/provider/ServiceProvider.java b/version2/src/main/java/part1/Server/provider/ServiceProvider.java deleted file mode 100644 index f7355dc..0000000 --- a/version2/src/main/java/part1/Server/provider/ServiceProvider.java +++ /dev/null @@ -1,47 +0,0 @@ -package part1.Server.provider; - -import part1.Server.serviceRegister.ServiceRegister; -import part1.Server.serviceRegister.impl.ZKServiceRegister; - -import java.net.InetSocketAddress; -import java.util.HashMap; -import java.util.Map; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/16 17:35 - */ -public class ServiceProvider { - private Map interfaceProvider; - - private int port; - private String host; - //注册服务类 - private ServiceRegister serviceRegister; - - public ServiceProvider(String host,int port){ - //需要传入服务端自身的网络地址 - this.host=host; - this.port=port; - this.interfaceProvider=new HashMap<>(); - this.serviceRegister=new ZKServiceRegister(); - } - - public void provideServiceInterface(Object service){ - String serviceName=service.getClass().getName(); - Class[] interfaceName=service.getClass().getInterfaces(); - - for (Class clazz:interfaceName){ - //本机的映射表 - interfaceProvider.put(clazz.getName(),service); - //在注册中心注册服务 - serviceRegister.register(clazz.getName(),new InetSocketAddress(host,port)); - } - } - - public Object getService(String interfaceName){ - return interfaceProvider.get(interfaceName); - } - -} diff --git a/version2/src/main/java/part1/Server/server/RpcServer.java b/version2/src/main/java/part1/Server/server/RpcServer.java deleted file mode 100644 index 7ed9584..0000000 --- a/version2/src/main/java/part1/Server/server/RpcServer.java +++ /dev/null @@ -1,11 +0,0 @@ -package part1.Server.server; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/12 11:26 - */ -public interface RpcServer { - void start(int port); - void stop(); -} diff --git a/version2/src/main/java/part1/Server/server/impl/NettyRPCRPCServer.java b/version2/src/main/java/part1/Server/server/impl/NettyRPCRPCServer.java deleted file mode 100644 index e3022e8..0000000 --- a/version2/src/main/java/part1/Server/server/impl/NettyRPCRPCServer.java +++ /dev/null @@ -1,48 +0,0 @@ -package part1.Server.server.impl; - -import io.netty.bootstrap.ServerBootstrap; -import io.netty.channel.ChannelFuture; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.nio.NioServerSocketChannel; -import lombok.AllArgsConstructor; -import part1.Server.provider.ServiceProvider; -import part1.Server.netty.nettyInitializer.NettyServerInitializer; -import part1.Server.server.RpcServer; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/26 14:01 - */ -@AllArgsConstructor -public class NettyRPCRPCServer implements RpcServer { - private ServiceProvider serviceProvider; - @Override - public void start(int port) { - // netty 服务线程组boss负责建立连接, work负责具体的请求 - NioEventLoopGroup bossGroup = new NioEventLoopGroup(); - NioEventLoopGroup workGroup = new NioEventLoopGroup(); - System.out.println("netty服务端启动了"); - try { - //启动netty服务器 - ServerBootstrap serverBootstrap = new ServerBootstrap(); - //初始化 - serverBootstrap.group(bossGroup,workGroup).channel(NioServerSocketChannel.class) - .childHandler(new NettyServerInitializer(serviceProvider)); - //同步堵塞 - ChannelFuture channelFuture=serverBootstrap.bind(port).sync(); - //死循环监听 - channelFuture.channel().closeFuture().sync(); - }catch (InterruptedException e){ - e.printStackTrace(); - }finally { - bossGroup.shutdownGracefully(); - workGroup.shutdownGracefully(); - } - } - - @Override - public void stop() { - - } -} diff --git a/version2/src/main/java/part1/Server/server/impl/SimpleRPCRPCServer.java b/version2/src/main/java/part1/Server/server/impl/SimpleRPCRPCServer.java deleted file mode 100644 index 277926e..0000000 --- a/version2/src/main/java/part1/Server/server/impl/SimpleRPCRPCServer.java +++ /dev/null @@ -1,39 +0,0 @@ -package part1.Server.server.impl; - - -import lombok.AllArgsConstructor; -import part1.Server.provider.ServiceProvider; -import part1.Server.server.work.WorkThread; -import part1.Server.server.RpcServer; - -import java.io.IOException; -import java.net.ServerSocket; -import java.net.Socket; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/12 11:37 - */ -@AllArgsConstructor -public class SimpleRPCRPCServer implements RpcServer { - private ServiceProvider serviceProvide; - @Override - public void start(int port) { - try { - ServerSocket serverSocket=new ServerSocket(port); - System.out.println("服务器启动了"); - while (true) { - Socket socket = serverSocket.accept(); - new Thread(new WorkThread(socket,serviceProvide)).start(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Override - public void stop() { - - } -} diff --git a/version2/src/main/java/part1/Server/server/work/WorkThread.java b/version2/src/main/java/part1/Server/server/work/WorkThread.java deleted file mode 100644 index 064b9c2..0000000 --- a/version2/src/main/java/part1/Server/server/work/WorkThread.java +++ /dev/null @@ -1,58 +0,0 @@ -package part1.Server.server.work; - - -import lombok.AllArgsConstructor; -import part1.Server.provider.ServiceProvider; -import part1.common.Message.RpcRequest; -import part1.common.Message.RpcResponse; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.Socket; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/14 17:39 - */ -@AllArgsConstructor -public class WorkThread implements Runnable{ - private Socket socket; - private ServiceProvider serviceProvide; - @Override - public void run() { - try { - ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream()); - ObjectInputStream ois=new ObjectInputStream(socket.getInputStream()); - //读取客户端传过来的request - RpcRequest rpcRequest = (RpcRequest) ois.readObject(); - //反射调用服务方法获取返回值 - RpcResponse rpcResponse=getResponse(rpcRequest); - //向客户端写入response - oos.writeObject(rpcResponse); - oos.flush(); - } catch (IOException | ClassNotFoundException e) { - e.printStackTrace(); - } - } - private RpcResponse getResponse(RpcRequest rpcRequest){ - //得到服务名 - String interfaceName=rpcRequest.getInterfaceName(); - //得到服务端相应服务实现类 - Object service = serviceProvide.getService(interfaceName); - //反射调用方法 - Method method=null; - try { - method= service.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParamsType()); - Object invoke=method.invoke(service,rpcRequest.getParams()); - return RpcResponse.sussess(invoke); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - e.printStackTrace(); - System.out.println("方法执行错误"); - return RpcResponse.fail(); - } - } -} diff --git a/version2/src/main/java/part1/Server/serviceRegister/ServiceRegister.java b/version2/src/main/java/part1/Server/serviceRegister/ServiceRegister.java deleted file mode 100644 index 54c52b1..0000000 --- a/version2/src/main/java/part1/Server/serviceRegister/ServiceRegister.java +++ /dev/null @@ -1,15 +0,0 @@ -package part1.Server.serviceRegister; - -import java.net.InetSocketAddress; - -/** - * @author wxx - * @version 1.0 - * @create 2024/5/3 16:58 - */ -// 服务注册接口 -public interface ServiceRegister { - // 注册:保存服务与地址。 - void register(String serviceName, InetSocketAddress serviceAddress); - -} diff --git a/version2/src/main/java/part1/Server/serviceRegister/impl/ZKServiceRegister.java b/version2/src/main/java/part1/Server/serviceRegister/impl/ZKServiceRegister.java deleted file mode 100644 index d569338..0000000 --- a/version2/src/main/java/part1/Server/serviceRegister/impl/ZKServiceRegister.java +++ /dev/null @@ -1,62 +0,0 @@ -package part1.Server.serviceRegister.impl; - -import org.apache.curator.RetryPolicy; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.retry.ExponentialBackoffRetry; -import org.apache.zookeeper.CreateMode; -import part1.Server.serviceRegister.ServiceRegister; - -import java.net.InetSocketAddress; -/** - * @author wxx - * @version 1.0 - * @create 2024/5/3 17:28 - */ -public class ZKServiceRegister implements ServiceRegister { - // curator 提供的zookeeper客户端 - private CuratorFramework client; - //zookeeper根路径节点 - private static final String ROOT_PATH = "MyRPC"; - - //负责zookeeper客户端的初始化,并与zookeeper服务端进行连接 - public ZKServiceRegister(){ - // 指数时间重试 - RetryPolicy policy = new ExponentialBackoffRetry(1000, 3); - // zookeeper的地址固定,不管是服务提供者还是,消费者都要与之建立连接 - // sessionTimeoutMs 与 zoo.cfg中的tickTime 有关系, - // zk还会根据minSessionTimeout与maxSessionTimeout两个参数重新调整最后的超时值。默认分别为tickTime 的2倍和20倍 - // 使用心跳监听状态 - this.client = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181") - .sessionTimeoutMs(40000).retryPolicy(policy).namespace(ROOT_PATH).build(); - this.client.start(); - System.out.println("zookeeper 连接成功"); - } - //注册服务到注册中心 - @Override - public void register(String serviceName, InetSocketAddress serviceAddress) { - try { - // serviceName创建成永久节点,服务提供者下线时,不删服务名,只删地址 - if(client.checkExists().forPath("/" + serviceName) == null){ - client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/" + serviceName); - } - // 路径地址,一个/代表一个节点 - String path = "/" + serviceName +"/"+ getServiceAddress(serviceAddress); - // 临时节点,服务器下线就删除节点 - client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path); - } catch (Exception e) { - System.out.println("此服务已存在"); - } - } - // 地址 -> XXX.XXX.XXX.XXX:port 字符串 - private String getServiceAddress(InetSocketAddress serverAddress) { - return serverAddress.getHostName() + - ":" + - serverAddress.getPort(); - } - // 字符串解析为地址 - private InetSocketAddress parseAddress(String address) { - String[] result = address.split(":"); - return new InetSocketAddress(result[0], Integer.parseInt(result[1])); - } -} diff --git a/version2/src/main/java/part1/common/Message/MessageType.java b/version2/src/main/java/part1/common/Message/MessageType.java deleted file mode 100644 index ebbcc83..0000000 --- a/version2/src/main/java/part1/common/Message/MessageType.java +++ /dev/null @@ -1,17 +0,0 @@ -package part1.common.Message; - -import lombok.AllArgsConstructor; - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/2 22:29 - */ -@AllArgsConstructor -public enum MessageType { - REQUEST(0),RESPONSE(1); - private int code; - public int getCode(){ - return code; - } -} \ No newline at end of file diff --git a/version2/src/main/java/part1/common/Message/RpcRequest.java b/version2/src/main/java/part1/common/Message/RpcRequest.java deleted file mode 100644 index 2642f38..0000000 --- a/version2/src/main/java/part1/common/Message/RpcRequest.java +++ /dev/null @@ -1,29 +0,0 @@ -package part1.common.Message; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.io.Serializable; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/1 18:30 - * 定义发送的消息格式 - */ -@NoArgsConstructor -@AllArgsConstructor -@Data -@Builder -public class RpcRequest implements Serializable { - //服务类名,客户端只知道接口 - private String interfaceName; - //调用的方法名 - private String methodName; - //参数列表 - private Object[] params; - //参数类型 - private Class[] paramsType; -} diff --git a/version2/src/main/java/part1/common/Message/RpcResponse.java b/version2/src/main/java/part1/common/Message/RpcResponse.java deleted file mode 100644 index 7a44b45..0000000 --- a/version2/src/main/java/part1/common/Message/RpcResponse.java +++ /dev/null @@ -1,35 +0,0 @@ -package part1.common.Message; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.io.Serializable; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/1 19:18 - */ -@NoArgsConstructor -@AllArgsConstructor -@Data -@Builder -public class RpcResponse implements Serializable { - //状态信息 - private int code; - private String message; - //更新:加入传输数据的类型,以便在自定义序列化器中解析 - private Class dataType; - //具体数据 - private Object data; - - public static RpcResponse sussess(Object data){ - return RpcResponse.builder().code(200).dataType(data.getClass()).data(data).build(); - } - public static RpcResponse fail(){ - return RpcResponse.builder().code(500).message("服务器发生错误").build(); - } -} - diff --git a/version2/src/main/java/part1/common/pojo/User.java b/version2/src/main/java/part1/common/pojo/User.java deleted file mode 100644 index d7cef8c..0000000 --- a/version2/src/main/java/part1/common/pojo/User.java +++ /dev/null @@ -1,25 +0,0 @@ -package part1.common.pojo; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.io.Serializable; - -/** - * @author wxx - * @version 1.0 - * @create 2024/1/28 17:50 - */ -@Builder -@Data -@NoArgsConstructor -@AllArgsConstructor -public class User implements Serializable { - // 客户端和服务端共有的 - private Integer id; - private String userName; - private Boolean sex; -} - diff --git a/version2/src/main/java/part1/common/serializer/myCode/MyDecoder.java b/version2/src/main/java/part1/common/serializer/myCode/MyDecoder.java deleted file mode 100644 index 8788c0e..0000000 --- a/version2/src/main/java/part1/common/serializer/myCode/MyDecoder.java +++ /dev/null @@ -1,42 +0,0 @@ -package part1.common.serializer.myCode; - -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.ByteToMessageDecoder; -import part1.common.Message.MessageType; -import part1.common.serializer.mySerializer.Serializer; - -import java.awt.*; -import java.util.List; - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/2 22:24 - * 按照自定义的消息格式解码数据 - */ -public class MyDecoder extends ByteToMessageDecoder { - @Override - protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List out) throws Exception { - //1.读取消息类型 - short messageType = in.readShort(); - // 现在还只支持request与response请求 - if(messageType != MessageType.REQUEST.getCode() && - messageType != MessageType.RESPONSE.getCode()){ - System.out.println("暂不支持此种数据"); - return; - } - //2.读取序列化的方式&类型 - short serializerType = in.readShort(); - Serializer serializer = Serializer.getSerializerByCode(serializerType); - if(serializer == null) - throw new RuntimeException("不存在对应的序列化器"); - //3.读取序列化数组长度 - int length = in.readInt(); - //4.读取序列化数组 - byte[] bytes=new byte[length]; - in.readBytes(bytes); - Object deserialize= serializer.deserialize(bytes, messageType); - out.add(deserialize); - } -} diff --git a/version2/src/main/java/part1/common/serializer/myCode/MyEncoder.java b/version2/src/main/java/part1/common/serializer/myCode/MyEncoder.java deleted file mode 100644 index 7ce0fd4..0000000 --- a/version2/src/main/java/part1/common/serializer/myCode/MyEncoder.java +++ /dev/null @@ -1,41 +0,0 @@ -package part1.common.serializer.myCode; - -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.MessageToByteEncoder; -import lombok.AllArgsConstructor; -import part1.common.Message.MessageType; -import part1.common.Message.RpcRequest; -import part1.common.Message.RpcResponse; -import part1.common.serializer.mySerializer.Serializer; - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/2 22:24 - * 依次按照自定义的消息格式写入,传入的数据为request或者response - * 需要持有一个serialize器,负责将传入的对象序列化成字节数组 - */ -@AllArgsConstructor -public class MyEncoder extends MessageToByteEncoder { - private Serializer serializer; - @Override - protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception { - System.out.println(msg.getClass()); - //1.写入消息类型 - if(msg instanceof RpcRequest){ - out.writeShort(MessageType.REQUEST.getCode()); - } - else if(msg instanceof RpcResponse){ - out.writeShort(MessageType.RESPONSE.getCode()); - } - //2.写入序列化方式 - out.writeShort(serializer.getType()); - //得到序列化数组 - byte[] serializeBytes = serializer.serialize(msg); - //3.写入长度 - out.writeInt(serializeBytes.length); - //4.写入序列化数组 - out.writeBytes(serializeBytes); - } -} diff --git a/version2/src/main/java/part1/common/serializer/mySerializer/JsonSerializer.java b/version2/src/main/java/part1/common/serializer/mySerializer/JsonSerializer.java deleted file mode 100644 index 39240cf..0000000 --- a/version2/src/main/java/part1/common/serializer/mySerializer/JsonSerializer.java +++ /dev/null @@ -1,65 +0,0 @@ -package part1.common.serializer.mySerializer; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import part1.common.Message.RpcRequest; -import part1.common.Message.RpcResponse; - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/2 22:31 - */ -public class JsonSerializer implements Serializer { - @Override - public byte[] serialize(Object obj) { - byte[] bytes = JSONObject.toJSONBytes(obj); - return bytes; - } - - @Override - public Object deserialize(byte[] bytes, int messageType) { - Object obj = null; - // 传输的消息分为request与response - switch (messageType){ - case 0: - RpcRequest request = JSON.parseObject(bytes, RpcRequest.class); - Object[] objects = new Object[request.getParams().length]; - // 把json字串转化成对应的对象, fastjson可以读出基本数据类型,不用转化 - // 对转换后的request中的params属性逐个进行类型判断 - for(int i = 0; i < objects.length; i++){ - Class paramsType = request.getParamsType()[i]; - //判断每个对象类型是否和paramsTypes中的一致 - if (!paramsType.isAssignableFrom(request.getParams()[i].getClass())){ - //如果不一致,就行进行类型转换 - objects[i] = JSONObject.toJavaObject((JSONObject) request.getParams()[i],request.getParamsType()[i]); - }else{ - //如果一致就直接赋给objects[i] - objects[i] = request.getParams()[i]; - } - } - request.setParams(objects); - obj = request; - break; - case 1: - RpcResponse response = JSON.parseObject(bytes, RpcResponse.class); - Class dataType = response.getDataType(); - //判断转化后的response对象中的data的类型是否正确 - if(! dataType.isAssignableFrom(response.getData().getClass())){ - response.setData(JSONObject.toJavaObject((JSONObject) response.getData(),dataType)); - } - obj = response; - break; - default: - System.out.println("暂时不支持此种消息"); - throw new RuntimeException(); - } - return obj; - } - - //1 代表json序列化方式 - @Override - public int getType() { - return 1; - } -} diff --git a/version2/src/main/java/part1/common/serializer/mySerializer/ObjectSerializer.java b/version2/src/main/java/part1/common/serializer/mySerializer/ObjectSerializer.java deleted file mode 100644 index 3eec03c..0000000 --- a/version2/src/main/java/part1/common/serializer/mySerializer/ObjectSerializer.java +++ /dev/null @@ -1,54 +0,0 @@ -package part1.common.serializer.mySerializer; - -import java.io.*; - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/2 22:36 - */ -public class ObjectSerializer implements Serializer { - //利用Java io 对象 -》字节数组 - @Override - public byte[] serialize(Object obj) { - byte[] bytes=null; - ByteArrayOutputStream bos=new ByteArrayOutputStream(); - try { - //是一个对象输出流,用于将 Java 对象序列化为字节流,并将其连接到bos上 - ObjectOutputStream oos = new ObjectOutputStream(bos); - oos.writeObject(obj); - //刷新 ObjectOutputStream,确保所有缓冲区中的数据都被写入到底层流中。 - oos.flush(); - //将bos其内部缓冲区中的数据转换为字节数组 - bytes = bos.toByteArray(); - oos.close(); - bos.close(); - } catch (IOException e) { - e.printStackTrace(); - } - return bytes; - } - - //字节数组 -》对象 - @Override - public Object deserialize(byte[] bytes, int messageType) { - Object obj = null; - ByteArrayInputStream bis = new ByteArrayInputStream(bytes); - try { - ObjectInputStream ois = new ObjectInputStream(bis); - obj = ois.readObject(); - ois.close(); - bis.close(); - } catch (IOException | ClassNotFoundException e) { - e.printStackTrace(); - } - return obj; - } - - //0 代表Java 原生序列器 - @Override - public int getType() { - return 0; - } -} - diff --git a/version2/src/main/java/part1/common/serializer/mySerializer/Serializer.java b/version2/src/main/java/part1/common/serializer/mySerializer/Serializer.java deleted file mode 100644 index e0829d0..0000000 --- a/version2/src/main/java/part1/common/serializer/mySerializer/Serializer.java +++ /dev/null @@ -1,29 +0,0 @@ -package part1.common.serializer.mySerializer; - - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/2 22:31 - */ -public interface Serializer { - // 把对象序列化成字节数组 - byte[] serialize(Object obj); - // 从字节数组反序列化成消息, 使用java自带序列化方式不用messageType也能得到相应的对象(序列化字节数组里包含类信息) - // 其它方式需指定消息格式,再根据message转化成相应的对象 - Object deserialize(byte[] bytes, int messageType); - // 返回使用的序列器,是哪个 - // 0:java自带序列化方式, 1: json序列化方式 - int getType(); - // 根据序号取出序列化器,暂时有两种实现方式,需要其它方式,实现这个接口即可 - static Serializer getSerializerByCode(int code){ - switch (code){ - case 0: - return new ObjectSerializer(); - case 1: - return new JsonSerializer(); - default: - return null; - } - } -} diff --git a/version2/src/main/java/part1/common/service/Impl/UserServiceImpl.java b/version2/src/main/java/part1/common/service/Impl/UserServiceImpl.java deleted file mode 100644 index 41cde93..0000000 --- a/version2/src/main/java/part1/common/service/Impl/UserServiceImpl.java +++ /dev/null @@ -1,32 +0,0 @@ -package part1.common.service.Impl; - - -import part1.common.service.UserService; -import part1.common.pojo.User; - -import java.util.Random; -import java.util.UUID; - -/** - * @author wxx - * @version 1.0 - * @create 2024/1/28 16:28 - */ -public class UserServiceImpl implements UserService { - @Override - public User getUserByUserId(Integer id) { - System.out.println("客户端查询了"+id+"的用户"); - // 模拟从数据库中取用户的行为 - Random random = new Random(); - User user = User.builder().userName(UUID.randomUUID().toString()) - .id(id) - .sex(random.nextBoolean()).build(); - return user; - } - - @Override - public Integer insertUserId(User user) { - System.out.println("插入数据成功"+user.getUserName()); - return user.getId(); - } -} \ No newline at end of file diff --git a/version2/src/main/java/part1/common/service/UserService.java b/version2/src/main/java/part1/common/service/UserService.java deleted file mode 100644 index 0e539bd..0000000 --- a/version2/src/main/java/part1/common/service/UserService.java +++ /dev/null @@ -1,16 +0,0 @@ -package part1.common.service; - - -import part1.common.pojo.User; - -/** - * @author wxx - * @version 1.0 - * @create 2024/1/28 16:27 - */ -public interface UserService { - // 客户端通过这个接口调用服务端的实现类 - User getUserByUserId(Integer id); - //新增一个功能 - Integer insertUserId(User user); -} diff --git a/version2/src/main/java/part2/Client/TestClient.java b/version2/src/main/java/part2/Client/TestClient.java deleted file mode 100644 index e1c3007..0000000 --- a/version2/src/main/java/part2/Client/TestClient.java +++ /dev/null @@ -1,28 +0,0 @@ -package part2.Client; - - -import part2.Client.proxy.ClientProxy; -import part2.common.pojo.User; -import part2.common.service.UserService; - - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/6 18:39 - */ - -public class TestClient { - public static void main(String[] args) throws InterruptedException { - ClientProxy clientProxy=new ClientProxy(); - //ClientProxy clientProxy=new part2.Client.proxy.ClientProxy("127.0.0.1",9999,0); - UserService proxy=clientProxy.getProxy(UserService.class); - - User user = proxy.getUserByUserId(1); - System.out.println("从服务端得到的user="+user.toString()); - - User u=User.builder().id(100).userName("wxx").sex(true).build(); - Integer id = proxy.insertUserId(u); - System.out.println("向服务端插入user的id"+id); - } -} diff --git a/version2/src/main/java/part2/Client/cache/serviceCache.java b/version2/src/main/java/part2/Client/cache/serviceCache.java deleted file mode 100644 index 4da39df..0000000 --- a/version2/src/main/java/part2/Client/cache/serviceCache.java +++ /dev/null @@ -1,54 +0,0 @@ -package part2.Client.cache; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/4 0:57 - */ -public class serviceCache { - //key: serviceName 服务名 - //value: addressList 服务提供者列表 - private static Map> cache=new HashMap<>(); - - //添加服务 - public void addServcieToCache(String serviceName,String address){ - if(cache.containsKey(serviceName)){ - List addressList = cache.get(serviceName); - addressList.add(address); - System.out.println("将name为"+serviceName+"和地址为"+address+"的服务添加到本地缓存中"); - }else { - List addressList=new ArrayList<>(); - addressList.add(address); - cache.put(serviceName,addressList); - } - } - //修改服务地址 - public void replaceServiceAddress(String serviceName,String oldAddress,String newAddress){ - if(cache.containsKey(serviceName)){ - List addressList=cache.get(serviceName); - addressList.remove(oldAddress); - addressList.add(newAddress); - }else { - System.out.println("修改失败,服务不存在"); - } - } - //从缓存中取服务地址 - public List getServcieFromCache(String serviceName){ - if(!cache.containsKey(serviceName)) { - return null; - } - List a=cache.get(serviceName); - return a; - } - //从缓存中删除服务地址 - public void delete(String serviceName,String address){ - List addressList = cache.get(serviceName); - addressList.remove(address); - System.out.println("将name为"+serviceName+"和地址为"+address+"的服务从本地缓存中删除"); - } -} diff --git a/version2/src/main/java/part2/Client/netty/handler/NettyClientHandler.java b/version2/src/main/java/part2/Client/netty/handler/NettyClientHandler.java deleted file mode 100644 index 95eaf28..0000000 --- a/version2/src/main/java/part2/Client/netty/handler/NettyClientHandler.java +++ /dev/null @@ -1,27 +0,0 @@ -package part2.Client.netty.handler; - -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.SimpleChannelInboundHandler; -import io.netty.util.AttributeKey; -import part2.common.Message.RpcResponse; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/26 17:29 - */ -public class NettyClientHandler extends SimpleChannelInboundHandler { - @Override - protected void channelRead0(ChannelHandlerContext ctx, RpcResponse response) throws Exception { - // 接收到response, 给channel设计别名,让sendRequest里读取response - AttributeKey key = AttributeKey.valueOf("RPCResponse"); - ctx.channel().attr(key).set(response); - ctx.channel().close(); - } - - @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { - cause.printStackTrace(); - ctx.close(); - } -} diff --git a/version2/src/main/java/part2/Client/netty/nettyInitializer/NettyClientInitializer.java b/version2/src/main/java/part2/Client/netty/nettyInitializer/NettyClientInitializer.java deleted file mode 100644 index 175c729..0000000 --- a/version2/src/main/java/part2/Client/netty/nettyInitializer/NettyClientInitializer.java +++ /dev/null @@ -1,26 +0,0 @@ -package part2.Client.netty.nettyInitializer; - - -import io.netty.channel.ChannelInitializer; -import io.netty.channel.ChannelPipeline; -import io.netty.channel.socket.SocketChannel; -import part2.Client.netty.handler.NettyClientHandler; -import part2.common.serializer.myCode.MyDecoder; -import part2.common.serializer.myCode.MyEncoder; -import part2.common.serializer.mySerializer.JsonSerializer; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/26 17:26 - */ -public class NettyClientInitializer extends ChannelInitializer { - @Override - protected void initChannel(SocketChannel ch) throws Exception { - ChannelPipeline pipeline = ch.pipeline(); - //使用自定义的编/解码器 - pipeline.addLast(new MyEncoder(new JsonSerializer())); - pipeline.addLast(new MyDecoder()); - pipeline.addLast(new NettyClientHandler()); - } -} diff --git a/version2/src/main/java/part2/Client/proxy/ClientProxy.java b/version2/src/main/java/part2/Client/proxy/ClientProxy.java deleted file mode 100644 index d549e0d..0000000 --- a/version2/src/main/java/part2/Client/proxy/ClientProxy.java +++ /dev/null @@ -1,42 +0,0 @@ -package part2.Client.proxy; - - -import part2.Client.rpcClient.RpcClient; -import part2.Client.rpcClient.impl.NettyRpcClient; -import part2.common.Message.RpcRequest; -import part2.common.Message.RpcResponse; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/6 16:49 - */ -public class ClientProxy implements InvocationHandler { - //传入参数service接口的class对象,反射封装成一个request - - private RpcClient rpcClient; - public ClientProxy() throws InterruptedException { - rpcClient=new NettyRpcClient(); - } - - //jdk动态代理,每一次代理对象调用方法,都会经过此方法增强(反射获取request对象,socket发送到服务端) - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - //构建request - RpcRequest request=RpcRequest.builder() - .interfaceName(method.getDeclaringClass().getName()) - .methodName(method.getName()) - .params(args).paramsType(method.getParameterTypes()).build(); - //数据传输 - RpcResponse response= rpcClient.sendRequest(request); - return response.getData(); - } - public T getProxy(Class clazz){ - Object o = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, this); - return (T)o; - } -} diff --git a/version2/src/main/java/part2/Client/rpcClient/RpcClient.java b/version2/src/main/java/part2/Client/rpcClient/RpcClient.java deleted file mode 100644 index 21690b1..0000000 --- a/version2/src/main/java/part2/Client/rpcClient/RpcClient.java +++ /dev/null @@ -1,15 +0,0 @@ -package part2.Client.rpcClient; - -import part2.common.Message.RpcRequest; -import part2.common.Message.RpcResponse; - -/** - * @author wxx - * @version 1.0 - * @create 2024/5/2 18:55 - */ -public interface RpcClient { - - //定义底层通信的方法 - RpcResponse sendRequest(RpcRequest request); -} diff --git a/version2/src/main/java/part2/Client/rpcClient/impl/NettyRpcClient.java b/version2/src/main/java/part2/Client/rpcClient/impl/NettyRpcClient.java deleted file mode 100644 index bf006a7..0000000 --- a/version2/src/main/java/part2/Client/rpcClient/impl/NettyRpcClient.java +++ /dev/null @@ -1,68 +0,0 @@ -package part2.Client.rpcClient.impl; - -import io.netty.bootstrap.Bootstrap; -import io.netty.channel.Channel; -import io.netty.channel.ChannelFuture; -import io.netty.channel.EventLoopGroup; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.nio.NioSocketChannel; -import io.netty.util.AttributeKey; -import part2.Client.netty.nettyInitializer.NettyClientInitializer; -import part2.Client.rpcClient.RpcClient; -import part2.Client.serviceCenter.ServiceCenter; -import part2.Client.serviceCenter.ZKServiceCenter; -import part2.common.Message.RpcRequest; -import part2.common.Message.RpcResponse; - -import java.net.InetSocketAddress; - -/** - * @author wxx - * @version 1.0 - * @create 2024/5/2 19:40 - */ -public class NettyRpcClient implements RpcClient { - - private static final Bootstrap bootstrap; - private static final EventLoopGroup eventLoopGroup; - - private ServiceCenter serviceCenter; - public NettyRpcClient() throws InterruptedException { - this.serviceCenter=new ZKServiceCenter(); - } - - //netty客户端初始化 - static { - eventLoopGroup = new NioEventLoopGroup(); - bootstrap = new Bootstrap(); - bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class) - .handler(new NettyClientInitializer()); - } - @Override - public RpcResponse sendRequest(RpcRequest request) { - //从注册中心获取host,post - InetSocketAddress address = serviceCenter.serviceDiscovery(request.getInterfaceName()); - String host = address.getHostName(); - int port = address.getPort(); - try { - ChannelFuture channelFuture = bootstrap.connect(host, port).sync(); - Channel channel = channelFuture.channel(); - // 发送数据 - channel.writeAndFlush(request); - //sync()堵塞获取结果 - channel.closeFuture().sync(); - // 阻塞的获得结果,通过给channel设计别名,获取特定名字下的channel中的内容(这个在hanlder中设置) - // AttributeKey是,线程隔离的,不会由线程安全问题。 - // 当前场景下选择堵塞获取结果 - // 其它场景也可以选择添加监听器的方式来异步获取结果 channelFuture.addListener... - AttributeKey key = AttributeKey.valueOf("RPCResponse"); - RpcResponse response = channel.attr(key).get(); - - System.out.println(response); - return response; - } catch (InterruptedException e) { - e.printStackTrace(); - } - return null; - } -} diff --git a/version2/src/main/java/part2/Client/rpcClient/impl/SimpleSocketRpcCilent.java b/version2/src/main/java/part2/Client/rpcClient/impl/SimpleSocketRpcCilent.java deleted file mode 100644 index 8faae62..0000000 --- a/version2/src/main/java/part2/Client/rpcClient/impl/SimpleSocketRpcCilent.java +++ /dev/null @@ -1,41 +0,0 @@ -package part2.Client.rpcClient.impl; - -import part2.Client.rpcClient.RpcClient; -import part2.common.Message.RpcRequest; -import part2.common.Message.RpcResponse; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.net.Socket; - -/** - * @author wxx - * @version 1.0 - * @create 2024/5/2 18:58 - */ -public class SimpleSocketRpcCilent implements RpcClient { - private String host; - private int port; - public SimpleSocketRpcCilent(String host,int port){ - this.host=host; - this.port=port; - } - @Override - public RpcResponse sendRequest(RpcRequest request) { - try { - Socket socket=new Socket(host, port); - ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream()); - ObjectInputStream ois=new ObjectInputStream(socket.getInputStream()); - - oos.writeObject(request); - oos.flush(); - - RpcResponse response=(RpcResponse) ois.readObject(); - return response; - } catch (IOException | ClassNotFoundException e) { - e.printStackTrace(); - return null; - } - } -} diff --git a/version2/src/main/java/part2/Client/serviceCenter/ServiceCenter.java b/version2/src/main/java/part2/Client/serviceCenter/ServiceCenter.java deleted file mode 100644 index d0562e6..0000000 --- a/version2/src/main/java/part2/Client/serviceCenter/ServiceCenter.java +++ /dev/null @@ -1,14 +0,0 @@ -package part2.Client.serviceCenter; - -import java.net.InetSocketAddress; - -/** - * @author wxx - * @version 1.0 - * @create 2024/5/3 21:42 - */ -//服务中心接口 -public interface ServiceCenter { - // 查询:根据服务名查找地址 - InetSocketAddress serviceDiscovery(String serviceName); -} diff --git a/version2/src/main/java/part2/Client/serviceCenter/ZKServiceCenter.java b/version2/src/main/java/part2/Client/serviceCenter/ZKServiceCenter.java deleted file mode 100644 index b53dec4..0000000 --- a/version2/src/main/java/part2/Client/serviceCenter/ZKServiceCenter.java +++ /dev/null @@ -1,75 +0,0 @@ -package part2.Client.serviceCenter; - -import org.apache.curator.RetryPolicy; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.retry.ExponentialBackoffRetry; -import part2.Client.cache.serviceCache; -import part2.Client.serviceCenter.ZkWatcher.watchZK; - -import java.net.InetSocketAddress; -import java.util.List; - -/** - * @author wxx - * @version 1.0 - * @create 2024/5/3 21:41 - */ -public class ZKServiceCenter implements ServiceCenter{ - // curator 提供的zookeeper客户端 - private CuratorFramework client; - //zookeeper根路径节点 - private static final String ROOT_PATH = "MyRPC"; - //serviceCache - private serviceCache cache; - - //负责zookeeper客户端的初始化,并与zookeeper服务端进行连接 - public ZKServiceCenter() throws InterruptedException { - // 指数时间重试 - RetryPolicy policy = new ExponentialBackoffRetry(1000, 3); - // zookeeper的地址固定,不管是服务提供者还是,消费者都要与之建立连接 - // sessionTimeoutMs 与 zoo.cfg中的tickTime 有关系, - // zk还会根据minSessionTimeout与maxSessionTimeout两个参数重新调整最后的超时值。默认分别为tickTime 的2倍和20倍 - // 使用心跳监听状态 - this.client = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181") - .sessionTimeoutMs(40000).retryPolicy(policy).namespace(ROOT_PATH).build(); - this.client.start(); - System.out.println("zookeeper 连接成功"); - //初始化本地缓存 - cache=new serviceCache(); - //加入zookeeper事件监听器 - watchZK watcher=new watchZK(client,cache); - //监听启动 - watcher.watchToUpdate(ROOT_PATH); - } - //根据服务名(接口名)返回地址 - @Override - public InetSocketAddress serviceDiscovery(String serviceName) { - try { - //先从本地缓存中找 - List serviceList=cache.getServcieFromCache(serviceName); - //如果找不到,再去zookeeper中找 - //这种i情况基本不会发生,或者说只会出现在初始化阶段 - if(serviceList==null) { - serviceList=client.getChildren().forPath("/" + serviceName); - } - // 这里默认用的第一个,后面加负载均衡 - String string = serviceList.get(0); - return parseAddress(string); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - // 地址 -> XXX.XXX.XXX.XXX:port 字符串 - private String getServiceAddress(InetSocketAddress serverAddress) { - return serverAddress.getHostName() + - ":" + - serverAddress.getPort(); - } - // 字符串解析为地址 - private InetSocketAddress parseAddress(String address) { - String[] result = address.split(":"); - return new InetSocketAddress(result[0], Integer.parseInt(result[1])); - } -} diff --git a/version2/src/main/java/part2/Client/serviceCenter/ZkWatcher/watchZK.java b/version2/src/main/java/part2/Client/serviceCenter/ZkWatcher/watchZK.java deleted file mode 100644 index 6d90bfe..0000000 --- a/version2/src/main/java/part2/Client/serviceCenter/ZkWatcher/watchZK.java +++ /dev/null @@ -1,87 +0,0 @@ -package part2.Client.serviceCenter.ZkWatcher; - -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.recipes.cache.ChildData; -import org.apache.curator.framework.recipes.cache.CuratorCache; -import org.apache.curator.framework.recipes.cache.CuratorCacheListener; -import part2.Client.cache.serviceCache; - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/4 1:00 - */ -public class watchZK { - // curator 提供的zookeeper客户端 - private CuratorFramework client; - //本地缓存 - serviceCache cache; - - public watchZK(CuratorFramework client,serviceCache cache){ - this.client=client; - this.cache=cache; - } - - /** - * 监听当前节点和子节点的 更新,创建,删除 - * @param path - */ - public void watchToUpdate(String path) throws InterruptedException { - CuratorCache curatorCache = CuratorCache.build(client, "/"); - curatorCache.listenable().addListener(new CuratorCacheListener() { - @Override - public void event(Type type, ChildData childData, ChildData childData1) { - // 第一个参数:事件类型(枚举) - // 第二个参数:节点更新前的状态、数据 - // 第三个参数:节点更新后的状态、数据 - // 创建节点时:节点刚被创建,不存在 更新前节点 ,所以第二个参数为 null - // 删除节点时:节点被删除,不存在 更新后节点 ,所以第三个参数为 null - // 节点创建时没有赋予值 create /curator/app1 只创建节点,在这种情况下,更新前节点的 data 为 null,获取不到更新前节点的数据 - switch (type.name()) { - case "NODE_CREATED": // 监听器第一次执行时节点存在也会触发次事件 - String[] pathList= pasrePath(childData1); - if(pathList.length<=2) break; - else { - String serviceName=pathList[1]; - String address=pathList[2]; - //将新注册的服务加入到本地缓存中 - cache.addServcieToCache(serviceName,address); - } - break; - case "NODE_CHANGED": // 节点更新 - if (childData.getData() != null) { - System.out.println("修改前的数据: " + new String(childData.getData())); - } else { - System.out.println("节点第一次赋值!"); - } - String[] oldPathList=pasrePath(childData); - String[] newPathList=pasrePath(childData1); - cache.replaceServiceAddress(oldPathList[1],oldPathList[2],newPathList[2]); - System.out.println("修改后的数据: " + new String(childData1.getData())); - break; - case "NODE_DELETED": // 节点删除 - String[] pathList_d= pasrePath(childData); - if(pathList_d.length<=2) break; - else { - String serviceName=pathList_d[1]; - String address=pathList_d[2]; - //将新注册的服务加入到本地缓存中 - cache.delete(serviceName,address); - } - break; - default: - break; - } - } - }); - //开启监听 - curatorCache.start(); - } - //解析节点对应地址 - public String[] pasrePath(ChildData childData){ - //获取更新的节点的路径 - String path=new String(childData.getPath()); - //按照格式 ,读取 - return path.split("/"); - } -} \ No newline at end of file diff --git a/version2/src/main/java/part2/Server/TestServer.java b/version2/src/main/java/part2/Server/TestServer.java deleted file mode 100644 index 694a5fe..0000000 --- a/version2/src/main/java/part2/Server/TestServer.java +++ /dev/null @@ -1,27 +0,0 @@ -package part2.Server; - - -import part2.Server.provider.ServiceProvider; -import part2.Server.server.RpcServer; -import part2.Server.server.impl.NettyRPCRPCServer; -import part2.common.service.Impl.UserServiceImpl; -import part2.common.service.UserService; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/11 19:39 - */ - -public class TestServer { - public static void main(String[] args) throws InterruptedException { - UserService userService=new UserServiceImpl(); - - ServiceProvider serviceProvider=new ServiceProvider("127.0.0.1",9999); - - serviceProvider.provideServiceInterface(userService); - - RpcServer rpcServer=new NettyRPCRPCServer(serviceProvider); - rpcServer.start(9999); - } -} diff --git a/version2/src/main/java/part2/Server/netty/handler/NettyRPCServerHandler.java b/version2/src/main/java/part2/Server/netty/handler/NettyRPCServerHandler.java deleted file mode 100644 index adefac7..0000000 --- a/version2/src/main/java/part2/Server/netty/handler/NettyRPCServerHandler.java +++ /dev/null @@ -1,51 +0,0 @@ -package part2.Server.netty.handler; - -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.SimpleChannelInboundHandler; -import lombok.AllArgsConstructor; -import part2.Server.provider.ServiceProvider; -import part2.common.Message.RpcRequest; -import part2.common.Message.RpcResponse; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/26 16:40 - * 因为是服务器端,我们知道接受到请求格式是RPCRequest - * Object类型也行,强制转型就行 - */ -@AllArgsConstructor -public class NettyRPCServerHandler extends SimpleChannelInboundHandler { - private ServiceProvider serviceProvider; - @Override - protected void channelRead0(ChannelHandlerContext ctx, RpcRequest request) throws Exception { - RpcResponse response = getResponse(request); - ctx.writeAndFlush(response); - ctx.close(); - } - @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { - cause.printStackTrace(); - ctx.close(); - } - private RpcResponse getResponse(RpcRequest rpcRequest){ - //得到服务名 - String interfaceName=rpcRequest.getInterfaceName(); - //得到服务端相应服务实现类 - Object service = serviceProvider.getService(interfaceName); - //反射调用方法 - Method method=null; - try { - method= service.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParamsType()); - Object invoke=method.invoke(service,rpcRequest.getParams()); - return RpcResponse.sussess(invoke); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - e.printStackTrace(); - System.out.println("方法执行错误"); - return RpcResponse.fail(); - } - } -} diff --git a/version2/src/main/java/part2/Server/netty/nettyInitializer/NettyServerInitializer.java b/version2/src/main/java/part2/Server/netty/nettyInitializer/NettyServerInitializer.java deleted file mode 100644 index 4d174a1..0000000 --- a/version2/src/main/java/part2/Server/netty/nettyInitializer/NettyServerInitializer.java +++ /dev/null @@ -1,30 +0,0 @@ -package part2.Server.netty.nettyInitializer; - - -import io.netty.channel.ChannelInitializer; -import io.netty.channel.ChannelPipeline; -import io.netty.channel.socket.SocketChannel; -import lombok.AllArgsConstructor; -import part2.Server.netty.handler.NettyRPCServerHandler; -import part2.Server.provider.ServiceProvider; -import part2.common.serializer.myCode.MyDecoder; -import part2.common.serializer.myCode.MyEncoder; -import part2.common.serializer.mySerializer.JsonSerializer; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/26 16:15 - */ -@AllArgsConstructor -public class NettyServerInitializer extends ChannelInitializer { - private ServiceProvider serviceProvider; - @Override - protected void initChannel(SocketChannel ch) throws Exception { - ChannelPipeline pipeline = ch.pipeline(); - //使用自定义的编/解码器 - pipeline.addLast(new MyEncoder(new JsonSerializer())); - pipeline.addLast(new MyDecoder()); - pipeline.addLast(new NettyRPCServerHandler(serviceProvider)); - } -} diff --git a/version2/src/main/java/part2/Server/provider/ServiceProvider.java b/version2/src/main/java/part2/Server/provider/ServiceProvider.java deleted file mode 100644 index f7265f4..0000000 --- a/version2/src/main/java/part2/Server/provider/ServiceProvider.java +++ /dev/null @@ -1,47 +0,0 @@ -package part2.Server.provider; - -import part2.Server.serviceRegister.ServiceRegister; -import part2.Server.serviceRegister.impl.ZKServiceRegister; - -import java.net.InetSocketAddress; -import java.util.HashMap; -import java.util.Map; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/16 17:35 - */ -public class ServiceProvider { - private Map interfaceProvider; - - private int port; - private String host; - //注册服务类 - private ServiceRegister serviceRegister; - - public ServiceProvider(String host,int port){ - //需要传入服务端自身的网络地址 - this.host=host; - this.port=port; - this.interfaceProvider=new HashMap<>(); - this.serviceRegister=new ZKServiceRegister(); - } - - public void provideServiceInterface(Object service){ - String serviceName=service.getClass().getName(); - Class[] interfaceName=service.getClass().getInterfaces(); - - for (Class clazz:interfaceName){ - //本机的映射表 - interfaceProvider.put(clazz.getName(),service); - //在注册中心注册服务 - serviceRegister.register(clazz.getName(),new InetSocketAddress(host,port)); - } - } - - public Object getService(String interfaceName){ - return interfaceProvider.get(interfaceName); - } - -} diff --git a/version2/src/main/java/part2/Server/server/RpcServer.java b/version2/src/main/java/part2/Server/server/RpcServer.java deleted file mode 100644 index 6abbf2a..0000000 --- a/version2/src/main/java/part2/Server/server/RpcServer.java +++ /dev/null @@ -1,11 +0,0 @@ -package part2.Server.server; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/12 11:26 - */ -public interface RpcServer { - void start(int port); - void stop(); -} diff --git a/version2/src/main/java/part2/Server/server/impl/NettyRPCRPCServer.java b/version2/src/main/java/part2/Server/server/impl/NettyRPCRPCServer.java deleted file mode 100644 index 7a4349a..0000000 --- a/version2/src/main/java/part2/Server/server/impl/NettyRPCRPCServer.java +++ /dev/null @@ -1,48 +0,0 @@ -package part2.Server.server.impl; - -import io.netty.bootstrap.ServerBootstrap; -import io.netty.channel.ChannelFuture; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.nio.NioServerSocketChannel; -import lombok.AllArgsConstructor; -import part2.Server.netty.nettyInitializer.NettyServerInitializer; -import part2.Server.provider.ServiceProvider; -import part2.Server.server.RpcServer; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/26 14:01 - */ -@AllArgsConstructor -public class NettyRPCRPCServer implements RpcServer { - private ServiceProvider serviceProvider; - @Override - public void start(int port) { - // netty 服务线程组boss负责建立连接, work负责具体的请求 - NioEventLoopGroup bossGroup = new NioEventLoopGroup(); - NioEventLoopGroup workGroup = new NioEventLoopGroup(); - System.out.println("netty服务端启动了"); - try { - //启动netty服务器 - ServerBootstrap serverBootstrap = new ServerBootstrap(); - //初始化 - serverBootstrap.group(bossGroup,workGroup).channel(NioServerSocketChannel.class) - .childHandler(new NettyServerInitializer(serviceProvider)); - //同步堵塞 - ChannelFuture channelFuture=serverBootstrap.bind(port).sync(); - //死循环监听 - channelFuture.channel().closeFuture().sync(); - }catch (InterruptedException e){ - e.printStackTrace(); - }finally { - bossGroup.shutdownGracefully(); - workGroup.shutdownGracefully(); - } - } - - @Override - public void stop() { - - } -} diff --git a/version2/src/main/java/part2/Server/server/impl/SimpleRPCRPCServer.java b/version2/src/main/java/part2/Server/server/impl/SimpleRPCRPCServer.java deleted file mode 100644 index 8033bab..0000000 --- a/version2/src/main/java/part2/Server/server/impl/SimpleRPCRPCServer.java +++ /dev/null @@ -1,39 +0,0 @@ -package part2.Server.server.impl; - - -import lombok.AllArgsConstructor; -import part2.Server.provider.ServiceProvider; -import part2.Server.server.RpcServer; -import part2.Server.server.work.WorkThread; - -import java.io.IOException; -import java.net.ServerSocket; -import java.net.Socket; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/12 11:37 - */ -@AllArgsConstructor -public class SimpleRPCRPCServer implements RpcServer { - private ServiceProvider serviceProvide; - @Override - public void start(int port) { - try { - ServerSocket serverSocket=new ServerSocket(port); - System.out.println("服务器启动了"); - while (true) { - Socket socket = serverSocket.accept(); - new Thread(new WorkThread(socket,serviceProvide)).start(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Override - public void stop() { - - } -} diff --git a/version2/src/main/java/part2/Server/server/work/WorkThread.java b/version2/src/main/java/part2/Server/server/work/WorkThread.java deleted file mode 100644 index a3985bf..0000000 --- a/version2/src/main/java/part2/Server/server/work/WorkThread.java +++ /dev/null @@ -1,58 +0,0 @@ -package part2.Server.server.work; - - -import lombok.AllArgsConstructor; -import part2.Server.provider.ServiceProvider; -import part2.common.Message.RpcRequest; -import part2.common.Message.RpcResponse; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.Socket; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/14 17:39 - */ -@AllArgsConstructor -public class WorkThread implements Runnable{ - private Socket socket; - private ServiceProvider serviceProvide; - @Override - public void run() { - try { - ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream()); - ObjectInputStream ois=new ObjectInputStream(socket.getInputStream()); - //读取客户端传过来的request - RpcRequest rpcRequest = (RpcRequest) ois.readObject(); - //反射调用服务方法获取返回值 - RpcResponse rpcResponse=getResponse(rpcRequest); - //向客户端写入response - oos.writeObject(rpcResponse); - oos.flush(); - } catch (IOException | ClassNotFoundException e) { - e.printStackTrace(); - } - } - private RpcResponse getResponse(RpcRequest rpcRequest){ - //得到服务名 - String interfaceName=rpcRequest.getInterfaceName(); - //得到服务端相应服务实现类 - Object service = serviceProvide.getService(interfaceName); - //反射调用方法 - Method method=null; - try { - method= service.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParamsType()); - Object invoke=method.invoke(service,rpcRequest.getParams()); - return RpcResponse.sussess(invoke); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - e.printStackTrace(); - System.out.println("方法执行错误"); - return RpcResponse.fail(); - } - } -} diff --git a/version2/src/main/java/part2/Server/serviceRegister/ServiceRegister.java b/version2/src/main/java/part2/Server/serviceRegister/ServiceRegister.java deleted file mode 100644 index a300602..0000000 --- a/version2/src/main/java/part2/Server/serviceRegister/ServiceRegister.java +++ /dev/null @@ -1,15 +0,0 @@ -package part2.Server.serviceRegister; - -import java.net.InetSocketAddress; - -/** - * @author wxx - * @version 1.0 - * @create 2024/5/3 16:58 - */ -// 服务注册接口 -public interface ServiceRegister { - // 注册:保存服务与地址。 - void register(String serviceName, InetSocketAddress serviceAddress); - -} diff --git a/version2/src/main/java/part2/Server/serviceRegister/impl/ZKServiceRegister.java b/version2/src/main/java/part2/Server/serviceRegister/impl/ZKServiceRegister.java deleted file mode 100644 index 6e1c006..0000000 --- a/version2/src/main/java/part2/Server/serviceRegister/impl/ZKServiceRegister.java +++ /dev/null @@ -1,62 +0,0 @@ -package part2.Server.serviceRegister.impl; - -import org.apache.curator.RetryPolicy; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.retry.ExponentialBackoffRetry; -import org.apache.zookeeper.CreateMode; -import part2.Server.serviceRegister.ServiceRegister; - -import java.net.InetSocketAddress; -/** - * @author wxx - * @version 1.0 - * @create 2024/5/3 17:28 - */ -public class ZKServiceRegister implements ServiceRegister { - // curator 提供的zookeeper客户端 - private CuratorFramework client; - //zookeeper根路径节点 - private static final String ROOT_PATH = "MyRPC"; - - //负责zookeeper客户端的初始化,并与zookeeper服务端进行连接 - public ZKServiceRegister(){ - // 指数时间重试 - RetryPolicy policy = new ExponentialBackoffRetry(1000, 3); - // zookeeper的地址固定,不管是服务提供者还是,消费者都要与之建立连接 - // sessionTimeoutMs 与 zoo.cfg中的tickTime 有关系, - // zk还会根据minSessionTimeout与maxSessionTimeout两个参数重新调整最后的超时值。默认分别为tickTime 的2倍和20倍 - // 使用心跳监听状态 - this.client = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181") - .sessionTimeoutMs(40000).retryPolicy(policy).namespace(ROOT_PATH).build(); - this.client.start(); - System.out.println("zookeeper 连接成功"); - } - //注册服务到注册中心 - @Override - public void register(String serviceName, InetSocketAddress serviceAddress) { - try { - // serviceName创建成永久节点,服务提供者下线时,不删服务名,只删地址 - if(client.checkExists().forPath("/" + serviceName) == null){ - client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/" + serviceName); - } - // 路径地址,一个/代表一个节点 - String path = "/" + serviceName +"/"+ getServiceAddress(serviceAddress); - // 临时节点,服务器下线就删除节点 - client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path); - } catch (Exception e) { - System.out.println("此服务已存在"); - } - } - // 地址 -> XXX.XXX.XXX.XXX:port 字符串 - private String getServiceAddress(InetSocketAddress serverAddress) { - return serverAddress.getHostName() + - ":" + - serverAddress.getPort(); - } - // 字符串解析为地址 - private InetSocketAddress parseAddress(String address) { - String[] result = address.split(":"); - return new InetSocketAddress(result[0], Integer.parseInt(result[1])); - } -} diff --git a/version2/src/main/java/part2/common/Message/MessageType.java b/version2/src/main/java/part2/common/Message/MessageType.java deleted file mode 100644 index 0241fd6..0000000 --- a/version2/src/main/java/part2/common/Message/MessageType.java +++ /dev/null @@ -1,17 +0,0 @@ -package part2.common.Message; - -import lombok.AllArgsConstructor; - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/2 22:29 - */ -@AllArgsConstructor -public enum MessageType { - REQUEST(0),RESPONSE(1); - private int code; - public int getCode(){ - return code; - } -} \ No newline at end of file diff --git a/version2/src/main/java/part2/common/Message/RpcRequest.java b/version2/src/main/java/part2/common/Message/RpcRequest.java deleted file mode 100644 index 9ed8c3a..0000000 --- a/version2/src/main/java/part2/common/Message/RpcRequest.java +++ /dev/null @@ -1,29 +0,0 @@ -package part2.common.Message; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.io.Serializable; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/1 18:30 - * 定义发送的消息格式 - */ -@NoArgsConstructor -@AllArgsConstructor -@Data -@Builder -public class RpcRequest implements Serializable { - //服务类名,客户端只知道接口 - private String interfaceName; - //调用的方法名 - private String methodName; - //参数列表 - private Object[] params; - //参数类型 - private Class[] paramsType; -} diff --git a/version2/src/main/java/part2/common/Message/RpcResponse.java b/version2/src/main/java/part2/common/Message/RpcResponse.java deleted file mode 100644 index 8df2e59..0000000 --- a/version2/src/main/java/part2/common/Message/RpcResponse.java +++ /dev/null @@ -1,35 +0,0 @@ -package part2.common.Message; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.io.Serializable; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/1 19:18 - */ -@NoArgsConstructor -@AllArgsConstructor -@Data -@Builder -public class RpcResponse implements Serializable { - //状态信息 - private int code; - private String message; - //更新:加入传输数据的类型,以便在自定义序列化器中解析 - private Class dataType; - //具体数据 - private Object data; - - public static RpcResponse sussess(Object data){ - return RpcResponse.builder().code(200).dataType(data.getClass()).data(data).build(); - } - public static RpcResponse fail(){ - return RpcResponse.builder().code(500).message("服务器发生错误").build(); - } -} - diff --git a/version2/src/main/java/part2/common/pojo/User.java b/version2/src/main/java/part2/common/pojo/User.java deleted file mode 100644 index bf999d7..0000000 --- a/version2/src/main/java/part2/common/pojo/User.java +++ /dev/null @@ -1,25 +0,0 @@ -package part2.common.pojo; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.io.Serializable; - -/** - * @author wxx - * @version 1.0 - * @create 2024/1/28 17:50 - */ -@Builder -@Data -@NoArgsConstructor -@AllArgsConstructor -public class User implements Serializable { - // 客户端和服务端共有的 - private Integer id; - private String userName; - private Boolean sex; -} - diff --git a/version2/src/main/java/part2/common/serializer/myCode/MyDecoder.java b/version2/src/main/java/part2/common/serializer/myCode/MyDecoder.java deleted file mode 100644 index 7970141..0000000 --- a/version2/src/main/java/part2/common/serializer/myCode/MyDecoder.java +++ /dev/null @@ -1,41 +0,0 @@ -package part2.common.serializer.myCode; - -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.ByteToMessageDecoder; -import part2.common.Message.MessageType; -import part2.common.serializer.mySerializer.Serializer; - -import java.util.List; - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/2 22:24 - * 按照自定义的消息格式解码数据 - */ -public class MyDecoder extends ByteToMessageDecoder { - @Override - protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List out) throws Exception { - //1.读取消息类型 - short messageType = in.readShort(); - // 现在还只支持request与response请求 - if(messageType != MessageType.REQUEST.getCode() && - messageType != MessageType.RESPONSE.getCode()){ - System.out.println("暂不支持此种数据"); - return; - } - //2.读取序列化的方式&类型 - short serializerType = in.readShort(); - Serializer serializer = Serializer.getSerializerByCode(serializerType); - if(serializer == null) - throw new RuntimeException("不存在对应的序列化器"); - //3.读取序列化数组长度 - int length = in.readInt(); - //4.读取序列化数组 - byte[] bytes=new byte[length]; - in.readBytes(bytes); - Object deserialize= serializer.deserialize(bytes, messageType); - out.add(deserialize); - } -} diff --git a/version2/src/main/java/part2/common/serializer/myCode/MyEncoder.java b/version2/src/main/java/part2/common/serializer/myCode/MyEncoder.java deleted file mode 100644 index c6ef573..0000000 --- a/version2/src/main/java/part2/common/serializer/myCode/MyEncoder.java +++ /dev/null @@ -1,41 +0,0 @@ -package part2.common.serializer.myCode; - -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.MessageToByteEncoder; -import lombok.AllArgsConstructor; -import part2.common.Message.MessageType; -import part2.common.Message.RpcRequest; -import part2.common.Message.RpcResponse; -import part2.common.serializer.mySerializer.Serializer; - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/2 22:24 - * 依次按照自定义的消息格式写入,传入的数据为request或者response - * 需要持有一个serialize器,负责将传入的对象序列化成字节数组 - */ -@AllArgsConstructor -public class MyEncoder extends MessageToByteEncoder { - private Serializer serializer; - @Override - protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception { - System.out.println(msg.getClass()); - //1.写入消息类型 - if(msg instanceof RpcRequest){ - out.writeShort(MessageType.REQUEST.getCode()); - } - else if(msg instanceof RpcResponse){ - out.writeShort(MessageType.RESPONSE.getCode()); - } - //2.写入序列化方式 - out.writeShort(serializer.getType()); - //得到序列化数组 - byte[] serializeBytes = serializer.serialize(msg); - //3.写入长度 - out.writeInt(serializeBytes.length); - //4.写入序列化数组 - out.writeBytes(serializeBytes); - } -} diff --git a/version2/src/main/java/part2/common/serializer/mySerializer/JsonSerializer.java b/version2/src/main/java/part2/common/serializer/mySerializer/JsonSerializer.java deleted file mode 100644 index 63c000b..0000000 --- a/version2/src/main/java/part2/common/serializer/mySerializer/JsonSerializer.java +++ /dev/null @@ -1,65 +0,0 @@ -package part2.common.serializer.mySerializer; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import part2.common.Message.RpcRequest; -import part2.common.Message.RpcResponse; - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/2 22:31 - */ -public class JsonSerializer implements Serializer { - @Override - public byte[] serialize(Object obj) { - byte[] bytes = JSONObject.toJSONBytes(obj); - return bytes; - } - - @Override - public Object deserialize(byte[] bytes, int messageType) { - Object obj = null; - // 传输的消息分为request与response - switch (messageType){ - case 0: - RpcRequest request = JSON.parseObject(bytes, RpcRequest.class); - Object[] objects = new Object[request.getParams().length]; - // 把json字串转化成对应的对象, fastjson可以读出基本数据类型,不用转化 - // 对转换后的request中的params属性逐个进行类型判断 - for(int i = 0; i < objects.length; i++){ - Class paramsType = request.getParamsType()[i]; - //判断每个对象类型是否和paramsTypes中的一致 - if (!paramsType.isAssignableFrom(request.getParams()[i].getClass())){ - //如果不一致,就行进行类型转换 - objects[i] = JSONObject.toJavaObject((JSONObject) request.getParams()[i],request.getParamsType()[i]); - }else{ - //如果一致就直接赋给objects[i] - objects[i] = request.getParams()[i]; - } - } - request.setParams(objects); - obj = request; - break; - case 1: - RpcResponse response = JSON.parseObject(bytes, RpcResponse.class); - Class dataType = response.getDataType(); - //判断转化后的response对象中的data的类型是否正确 - if(! dataType.isAssignableFrom(response.getData().getClass())){ - response.setData(JSONObject.toJavaObject((JSONObject) response.getData(),dataType)); - } - obj = response; - break; - default: - System.out.println("暂时不支持此种消息"); - throw new RuntimeException(); - } - return obj; - } - - //1 代表json序列化方式 - @Override - public int getType() { - return 1; - } -} diff --git a/version2/src/main/java/part2/common/serializer/mySerializer/ObjectSerializer.java b/version2/src/main/java/part2/common/serializer/mySerializer/ObjectSerializer.java deleted file mode 100644 index 5940fb1..0000000 --- a/version2/src/main/java/part2/common/serializer/mySerializer/ObjectSerializer.java +++ /dev/null @@ -1,54 +0,0 @@ -package part2.common.serializer.mySerializer; - -import java.io.*; - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/2 22:36 - */ -public class ObjectSerializer implements Serializer { - //利用Java io 对象 -》字节数组 - @Override - public byte[] serialize(Object obj) { - byte[] bytes=null; - ByteArrayOutputStream bos=new ByteArrayOutputStream(); - try { - //是一个对象输出流,用于将 Java 对象序列化为字节流,并将其连接到bos上 - ObjectOutputStream oos = new ObjectOutputStream(bos); - oos.writeObject(obj); - //刷新 ObjectOutputStream,确保所有缓冲区中的数据都被写入到底层流中。 - oos.flush(); - //将bos其内部缓冲区中的数据转换为字节数组 - bytes = bos.toByteArray(); - oos.close(); - bos.close(); - } catch (IOException e) { - e.printStackTrace(); - } - return bytes; - } - - //字节数组 -》对象 - @Override - public Object deserialize(byte[] bytes, int messageType) { - Object obj = null; - ByteArrayInputStream bis = new ByteArrayInputStream(bytes); - try { - ObjectInputStream ois = new ObjectInputStream(bis); - obj = ois.readObject(); - ois.close(); - bis.close(); - } catch (IOException | ClassNotFoundException e) { - e.printStackTrace(); - } - return obj; - } - - //0 代表Java 原生序列器 - @Override - public int getType() { - return 0; - } -} - diff --git a/version2/src/main/java/part2/common/serializer/mySerializer/Serializer.java b/version2/src/main/java/part2/common/serializer/mySerializer/Serializer.java deleted file mode 100644 index c751d36..0000000 --- a/version2/src/main/java/part2/common/serializer/mySerializer/Serializer.java +++ /dev/null @@ -1,29 +0,0 @@ -package part2.common.serializer.mySerializer; - - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/2 22:31 - */ -public interface Serializer { - // 把对象序列化成字节数组 - byte[] serialize(Object obj); - // 从字节数组反序列化成消息, 使用java自带序列化方式不用messageType也能得到相应的对象(序列化字节数组里包含类信息) - // 其它方式需指定消息格式,再根据message转化成相应的对象 - Object deserialize(byte[] bytes, int messageType); - // 返回使用的序列器,是哪个 - // 0:java自带序列化方式, 1: json序列化方式 - int getType(); - // 根据序号取出序列化器,暂时有两种实现方式,需要其它方式,实现这个接口即可 - static Serializer getSerializerByCode(int code){ - switch (code){ - case 0: - return new ObjectSerializer(); - case 1: - return new JsonSerializer(); - default: - return null; - } - } -} diff --git a/version2/src/main/java/part2/common/service/Impl/UserServiceImpl.java b/version2/src/main/java/part2/common/service/Impl/UserServiceImpl.java deleted file mode 100644 index 37e6262..0000000 --- a/version2/src/main/java/part2/common/service/Impl/UserServiceImpl.java +++ /dev/null @@ -1,32 +0,0 @@ -package part2.common.service.Impl; - - -import part2.common.pojo.User; -import part2.common.service.UserService; - -import java.util.Random; -import java.util.UUID; - -/** - * @author wxx - * @version 1.0 - * @create 2024/1/28 16:28 - */ -public class UserServiceImpl implements UserService { - @Override - public User getUserByUserId(Integer id) { - System.out.println("客户端查询了"+id+"的用户"); - // 模拟从数据库中取用户的行为 - Random random = new Random(); - User user = User.builder().userName(UUID.randomUUID().toString()) - .id(id) - .sex(random.nextBoolean()).build(); - return user; - } - - @Override - public Integer insertUserId(User user) { - System.out.println("插入数据成功"+user.getUserName()); - return user.getId(); - } -} \ No newline at end of file diff --git a/version2/src/main/java/part2/common/service/UserService.java b/version2/src/main/java/part2/common/service/UserService.java deleted file mode 100644 index b6817fe..0000000 --- a/version2/src/main/java/part2/common/service/UserService.java +++ /dev/null @@ -1,16 +0,0 @@ -package part2.common.service; - - -import part2.common.pojo.User; - -/** - * @author wxx - * @version 1.0 - * @create 2024/1/28 16:27 - */ -public interface UserService { - // 客户端通过这个接口调用服务端的实现类 - User getUserByUserId(Integer id); - //新增一个功能 - Integer insertUserId(User user); -} diff --git a/version2/src/main/resources/log4j.properties b/version2/src/main/resources/log4j.properties deleted file mode 100644 index 4e012fe..0000000 --- a/version2/src/main/resources/log4j.properties +++ /dev/null @@ -1,8 +0,0 @@ -log4j.rootLogger=ERROR, stdout -log4j.appender.stdout=org.apache.log4j.ConsoleAppender - -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n -log4j.appender.logfile=org.apache.log4j.FileAppender -log4j.appender.logfile.File=target/spring.log log4j.appender.logfile.layout=org.apache.log4j.PatternLayout -log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n diff --git a/version3/pom.xml b/version3/pom.xml deleted file mode 100644 index 2484083..0000000 --- a/version3/pom.xml +++ /dev/null @@ -1,58 +0,0 @@ - - - 4.0.0 - - org.example - version3 - 1.0-SNAPSHOT - - - 8 - 8 - UTF-8 - - - - org.projectlombok - lombok - 1.18.30 - compile - - - org.slf4j - slf4j-log4j12 - 1.7.25 - - - org.apache.logging.log4j - log4j-1.2-api - 2.8.2 - - - - io.netty - netty-all - 4.1.51.Final - compile - - - - org.apache.curator - curator-recipes - 5.1.0 - - - com.alibaba - fastjson - 1.2.83 - - - com.github.rholder - guava-retrying - 2.0.0 - - - - \ No newline at end of file diff --git a/version3/src/main/java/part1/Client/TestClient.java b/version3/src/main/java/part1/Client/TestClient.java deleted file mode 100644 index 2c80f33..0000000 --- a/version3/src/main/java/part1/Client/TestClient.java +++ /dev/null @@ -1,28 +0,0 @@ -package part1.Client; - - -import part1.Client.proxy.ClientProxy; -import part1.common.pojo.User; -import part1.common.service.UserService; - - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/6 18:39 - */ - -public class TestClient { - public static void main(String[] args) throws InterruptedException { - ClientProxy clientProxy=new ClientProxy(); - //ClientProxy clientProxy=new proxy.Client.part1.ClientProxy("127.0.0.1",9999,0); - UserService proxy=clientProxy.getProxy(UserService.class); - - User user = proxy.getUserByUserId(1); - System.out.println("从服务端得到的user="+user.toString()); - - User u=User.builder().id(100).userName("wxx").sex(true).build(); - Integer id = proxy.insertUserId(u); - System.out.println("向服务端插入user的id"+id); - } -} diff --git a/version3/src/main/java/part1/Client/cache/serviceCache.java b/version3/src/main/java/part1/Client/cache/serviceCache.java deleted file mode 100644 index dee03ce..0000000 --- a/version3/src/main/java/part1/Client/cache/serviceCache.java +++ /dev/null @@ -1,57 +0,0 @@ -package part1.Client.cache; - -import part1.Client.serviceCenter.balance.LoadBalance; -import part1.Client.serviceCenter.balance.impl.ConsistencyHashBalance; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/4 0:57 - */ -public class serviceCache { - //key: serviceName 服务名 - //value: addressList 服务提供者列表 - private static Map> cache=new HashMap<>(); - - //添加服务 - public void addServcieToCache(String serviceName,String address){ - if(cache.containsKey(serviceName)){ - List addressList = cache.get(serviceName); - addressList.add(address); - System.out.println("将name为"+serviceName+"和地址为"+address+"的服务添加到本地缓存中"); - }else { - List addressList=new ArrayList<>(); - addressList.add(address); - cache.put(serviceName,addressList); - } - } - //修改服务地址 - public void replaceServiceAddress(String serviceName,String oldAddress,String newAddress){ - if(cache.containsKey(serviceName)){ - List addressList=cache.get(serviceName); - addressList.remove(oldAddress); - addressList.add(newAddress); - }else { - System.out.println("修改失败,服务不存在"); - } - } - //从缓存中取服务地址列表 - public List getServiceListFromCache(String serviceName){ - if(!cache.containsKey(serviceName)) { - return null; - } - return cache.get(serviceName); - } - - //从缓存中删除服务地址 - public void delete(String serviceName,String address){ - List addressList = cache.get(serviceName); - addressList.remove(address); - System.out.println("将name为"+serviceName+"和地址为"+address+"的服务从本地缓存中删除"); - } -} diff --git a/version3/src/main/java/part1/Client/netty/handler/NettyClientHandler.java b/version3/src/main/java/part1/Client/netty/handler/NettyClientHandler.java deleted file mode 100644 index 31858c6..0000000 --- a/version3/src/main/java/part1/Client/netty/handler/NettyClientHandler.java +++ /dev/null @@ -1,27 +0,0 @@ -package part1.Client.netty.handler; - -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.SimpleChannelInboundHandler; -import io.netty.util.AttributeKey; -import part1.common.Message.RpcResponse; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/26 17:29 - */ -public class NettyClientHandler extends SimpleChannelInboundHandler { - @Override - protected void channelRead0(ChannelHandlerContext ctx, RpcResponse response) throws Exception { - // 接收到response, 给channel设计别名,让sendRequest里读取response - AttributeKey key = AttributeKey.valueOf("RPCResponse"); - ctx.channel().attr(key).set(response); - ctx.channel().close(); - } - - @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { - cause.printStackTrace(); - ctx.close(); - } -} diff --git a/version3/src/main/java/part1/Client/netty/nettyInitializer/NettyClientInitializer.java b/version3/src/main/java/part1/Client/netty/nettyInitializer/NettyClientInitializer.java deleted file mode 100644 index e0b520a..0000000 --- a/version3/src/main/java/part1/Client/netty/nettyInitializer/NettyClientInitializer.java +++ /dev/null @@ -1,26 +0,0 @@ -package part1.Client.netty.nettyInitializer; - - -import io.netty.channel.ChannelInitializer; -import io.netty.channel.ChannelPipeline; -import io.netty.channel.socket.SocketChannel; -import part1.Client.netty.handler.NettyClientHandler; -import part1.common.serializer.myCode.MyDecoder; -import part1.common.serializer.myCode.MyEncoder; -import part1.common.serializer.mySerializer.JsonSerializer; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/26 17:26 - */ -public class NettyClientInitializer extends ChannelInitializer { - @Override - protected void initChannel(SocketChannel ch) throws Exception { - ChannelPipeline pipeline = ch.pipeline(); - //使用自定义的编/解码器 - pipeline.addLast(new MyEncoder(new JsonSerializer())); - pipeline.addLast(new MyDecoder()); - pipeline.addLast(new NettyClientHandler()); - } -} diff --git a/version3/src/main/java/part1/Client/proxy/ClientProxy.java b/version3/src/main/java/part1/Client/proxy/ClientProxy.java deleted file mode 100644 index bacca21..0000000 --- a/version3/src/main/java/part1/Client/proxy/ClientProxy.java +++ /dev/null @@ -1,42 +0,0 @@ -package part1.Client.proxy; - - -import part1.Client.rpcClient.RpcClient; -import part1.common.Message.RpcRequest; -import part1.common.Message.RpcResponse; -import part1.Client.rpcClient.impl.NettyRpcClient; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/6 16:49 - */ -public class ClientProxy implements InvocationHandler { - //传入参数service接口的class对象,反射封装成一个request - - private RpcClient rpcClient; - public ClientProxy() throws InterruptedException { - rpcClient=new NettyRpcClient(); - } - - //jdk动态代理,每一次代理对象调用方法,都会经过此方法增强(反射获取request对象,socket发送到服务端) - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - //构建request - RpcRequest request=RpcRequest.builder() - .interfaceName(method.getDeclaringClass().getName()) - .methodName(method.getName()) - .params(args).paramsType(method.getParameterTypes()).build(); - //数据传输 - RpcResponse response= rpcClient.sendRequest(request); - return response.getData(); - } - public T getProxy(Class clazz){ - Object o = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, this); - return (T)o; - } -} diff --git a/version3/src/main/java/part1/Client/rpcClient/RpcClient.java b/version3/src/main/java/part1/Client/rpcClient/RpcClient.java deleted file mode 100644 index c665530..0000000 --- a/version3/src/main/java/part1/Client/rpcClient/RpcClient.java +++ /dev/null @@ -1,15 +0,0 @@ -package part1.Client.rpcClient; - -import part1.common.Message.RpcRequest; -import part1.common.Message.RpcResponse; - -/** - * @author wxx - * @version 1.0 - * @create 2024/5/2 18:55 - */ -public interface RpcClient { - - //定义底层通信的方法 - RpcResponse sendRequest(RpcRequest request); -} diff --git a/version3/src/main/java/part1/Client/rpcClient/impl/NettyRpcClient.java b/version3/src/main/java/part1/Client/rpcClient/impl/NettyRpcClient.java deleted file mode 100644 index 0daab8c..0000000 --- a/version3/src/main/java/part1/Client/rpcClient/impl/NettyRpcClient.java +++ /dev/null @@ -1,68 +0,0 @@ -package part1.Client.rpcClient.impl; - -import io.netty.bootstrap.Bootstrap; -import io.netty.channel.Channel; -import io.netty.channel.ChannelFuture; -import io.netty.channel.EventLoopGroup; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.nio.NioSocketChannel; -import io.netty.util.AttributeKey; -import part1.Client.rpcClient.RpcClient; -import part1.Client.serviceCenter.ServiceCenter; -import part1.Client.serviceCenter.ZKServiceCenter; -import part1.common.Message.RpcRequest; -import part1.common.Message.RpcResponse; -import part1.Client.netty.nettyInitializer.NettyClientInitializer; - -import java.net.InetSocketAddress; - -/** - * @author wxx - * @version 1.0 - * @create 2024/5/2 19:40 - */ -public class NettyRpcClient implements RpcClient { - - private static final Bootstrap bootstrap; - private static final EventLoopGroup eventLoopGroup; - - private ServiceCenter serviceCenter; - public NettyRpcClient() throws InterruptedException { - this.serviceCenter=new ZKServiceCenter(); - } - - //netty客户端初始化 - static { - eventLoopGroup = new NioEventLoopGroup(); - bootstrap = new Bootstrap(); - bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class) - .handler(new NettyClientInitializer()); - } - @Override - public RpcResponse sendRequest(RpcRequest request) { - //从注册中心获取host,post - InetSocketAddress address = serviceCenter.serviceDiscovery(request.getInterfaceName()); - String host = address.getHostName(); - int port = address.getPort(); - try { - ChannelFuture channelFuture = bootstrap.connect(host, port).sync(); - Channel channel = channelFuture.channel(); - // 发送数据 - channel.writeAndFlush(request); - //sync()堵塞获取结果 - channel.closeFuture().sync(); - // 阻塞的获得结果,通过给channel设计别名,获取特定名字下的channel中的内容(这个在hanlder中设置) - // AttributeKey是,线程隔离的,不会由线程安全问题。 - // 当前场景下选择堵塞获取结果 - // 其它场景也可以选择添加监听器的方式来异步获取结果 channelFuture.addListener... - AttributeKey key = AttributeKey.valueOf("RPCResponse"); - RpcResponse response = channel.attr(key).get(); - - System.out.println(response); - return response; - } catch (InterruptedException e) { - e.printStackTrace(); - } - return null; - } -} diff --git a/version3/src/main/java/part1/Client/rpcClient/impl/SimpleSocketRpcCilent.java b/version3/src/main/java/part1/Client/rpcClient/impl/SimpleSocketRpcCilent.java deleted file mode 100644 index d74af41..0000000 --- a/version3/src/main/java/part1/Client/rpcClient/impl/SimpleSocketRpcCilent.java +++ /dev/null @@ -1,41 +0,0 @@ -package part1.Client.rpcClient.impl; - -import part1.Client.rpcClient.RpcClient; -import part1.common.Message.RpcRequest; -import part1.common.Message.RpcResponse; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.net.Socket; - -/** - * @author wxx - * @version 1.0 - * @create 2024/5/2 18:58 - */ -public class SimpleSocketRpcCilent implements RpcClient { - private String host; - private int port; - public SimpleSocketRpcCilent(String host,int port){ - this.host=host; - this.port=port; - } - @Override - public RpcResponse sendRequest(RpcRequest request) { - try { - Socket socket=new Socket(host, port); - ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream()); - ObjectInputStream ois=new ObjectInputStream(socket.getInputStream()); - - oos.writeObject(request); - oos.flush(); - - RpcResponse response=(RpcResponse) ois.readObject(); - return response; - } catch (IOException | ClassNotFoundException e) { - e.printStackTrace(); - return null; - } - } -} diff --git a/version3/src/main/java/part1/Client/serviceCenter/ServiceCenter.java b/version3/src/main/java/part1/Client/serviceCenter/ServiceCenter.java deleted file mode 100644 index 1842b94..0000000 --- a/version3/src/main/java/part1/Client/serviceCenter/ServiceCenter.java +++ /dev/null @@ -1,14 +0,0 @@ -package part1.Client.serviceCenter; - -import java.net.InetSocketAddress; - -/** - * @author wxx - * @version 1.0 - * @create 2024/5/3 21:42 - */ -//服务中心接口 -public interface ServiceCenter { - // 查询:根据服务名查找地址 - InetSocketAddress serviceDiscovery(String serviceName); -} diff --git a/version3/src/main/java/part1/Client/serviceCenter/ZKServiceCenter.java b/version3/src/main/java/part1/Client/serviceCenter/ZKServiceCenter.java deleted file mode 100644 index 0a23a1f..0000000 --- a/version3/src/main/java/part1/Client/serviceCenter/ZKServiceCenter.java +++ /dev/null @@ -1,76 +0,0 @@ -package part1.Client.serviceCenter; - -import org.apache.curator.RetryPolicy; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.retry.ExponentialBackoffRetry; -import part1.Client.cache.serviceCache; -import part1.Client.serviceCenter.ZkWatcher.watchZK; -import part1.Client.serviceCenter.balance.impl.ConsistencyHashBalance; - -import java.net.InetSocketAddress; -import java.util.List; - -/** - * @author wxx - * @version 1.0 - * @create 2024/5/3 21:41 - */ -public class ZKServiceCenter implements ServiceCenter{ - // curator 提供的zookeeper客户端 - private CuratorFramework client; - //zookeeper根路径节点 - private static final String ROOT_PATH = "MyRPC"; - //serviceCache - private serviceCache cache; - - //负责zookeeper客户端的初始化,并与zookeeper服务端进行连接 - public ZKServiceCenter() throws InterruptedException { - // 指数时间重试 - RetryPolicy policy = new ExponentialBackoffRetry(1000, 3); - // zookeeper的地址固定,不管是服务提供者还是,消费者都要与之建立连接 - // sessionTimeoutMs 与 zoo.cfg中的tickTime 有关系, - // zk还会根据minSessionTimeout与maxSessionTimeout两个参数重新调整最后的超时值。默认分别为tickTime 的2倍和20倍 - // 使用心跳监听状态 - this.client = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181") - .sessionTimeoutMs(40000).retryPolicy(policy).namespace(ROOT_PATH).build(); - this.client.start(); - System.out.println("zookeeper 连接成功"); - //初始化本地缓存 - cache=new serviceCache(); - //加入zookeeper事件监听器 - watchZK watcher=new watchZK(client,cache); - //监听启动 - watcher.watchToUpdate(ROOT_PATH); - } - //根据服务名(接口名)返回地址 - @Override - public InetSocketAddress serviceDiscovery(String serviceName) { - try { - //先从本地缓存中找 - List serviceList=cache.getServiceListFromCache(serviceName); - //如果找不到,再去zookeeper中找 - //这种i情况基本不会发生,或者说只会出现在初始化阶段 - if(serviceList==null) { - serviceList=client.getChildren().forPath("/" + serviceName); - } - // 负载均衡得到地址 - String address = new ConsistencyHashBalance().balance(serviceList); - return parseAddress(address); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - // 地址 -> XXX.XXX.XXX.XXX:port 字符串 - private String getServiceAddress(InetSocketAddress serverAddress) { - return serverAddress.getHostName() + - ":" + - serverAddress.getPort(); - } - // 字符串解析为地址 - private InetSocketAddress parseAddress(String address) { - String[] result = address.split(":"); - return new InetSocketAddress(result[0], Integer.parseInt(result[1])); - } -} diff --git a/version3/src/main/java/part1/Client/serviceCenter/ZkWatcher/watchZK.java b/version3/src/main/java/part1/Client/serviceCenter/ZkWatcher/watchZK.java deleted file mode 100644 index c8ef382..0000000 --- a/version3/src/main/java/part1/Client/serviceCenter/ZkWatcher/watchZK.java +++ /dev/null @@ -1,87 +0,0 @@ -package part1.Client.serviceCenter.ZkWatcher; - -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.recipes.cache.ChildData; -import org.apache.curator.framework.recipes.cache.CuratorCache; -import org.apache.curator.framework.recipes.cache.CuratorCacheListener; -import part1.Client.cache.serviceCache; - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/4 1:00 - */ -public class watchZK { - // curator 提供的zookeeper客户端 - private CuratorFramework client; - //本地缓存 - serviceCache cache; - - public watchZK(CuratorFramework client, serviceCache cache){ - this.client=client; - this.cache=cache; - } - - /** - * 监听当前节点和子节点的 更新,创建,删除 - * @param path - */ - public void watchToUpdate(String path) throws InterruptedException { - CuratorCache curatorCache = CuratorCache.build(client, "/"); - curatorCache.listenable().addListener(new CuratorCacheListener() { - @Override - public void event(Type type, ChildData childData, ChildData childData1) { - // 第一个参数:事件类型(枚举) - // 第二个参数:节点更新前的状态、数据 - // 第三个参数:节点更新后的状态、数据 - // 创建节点时:节点刚被创建,不存在 更新前节点 ,所以第二个参数为 null - // 删除节点时:节点被删除,不存在 更新后节点 ,所以第三个参数为 null - // 节点创建时没有赋予值 create /curator/app1 只创建节点,在这种情况下,更新前节点的 data 为 null,获取不到更新前节点的数据 - switch (type.name()) { - case "NODE_CREATED": // 监听器第一次执行时节点存在也会触发次事件 - String[] pathList= pasrePath(childData1); - if(pathList.length<=2) break; - else { - String serviceName=pathList[1]; - String address=pathList[2]; - //将新注册的服务加入到本地缓存中 - cache.addServcieToCache(serviceName,address); - } - break; - case "NODE_CHANGED": // 节点更新 - if (childData.getData() != null) { - System.out.println("修改前的数据: " + new String(childData.getData())); - } else { - System.out.println("节点第一次赋值!"); - } - String[] oldPathList=pasrePath(childData); - String[] newPathList=pasrePath(childData1); - cache.replaceServiceAddress(oldPathList[1],oldPathList[2],newPathList[2]); - System.out.println("修改后的数据: " + new String(childData1.getData())); - break; - case "NODE_DELETED": // 节点删除 - String[] pathList_d= pasrePath(childData); - if(pathList_d.length<=2) break; - else { - String serviceName=pathList_d[1]; - String address=pathList_d[2]; - //将新注册的服务加入到本地缓存中 - cache.delete(serviceName,address); - } - break; - default: - break; - } - } - }); - //开启监听 - curatorCache.start(); - } - //解析节点对应地址 - public String[] pasrePath(ChildData childData){ - //获取更新的节点的路径 - String path=new String(childData.getPath()); - //按照格式 ,读取 - return path.split("/"); - } -} \ No newline at end of file diff --git a/version3/src/main/java/part1/Client/serviceCenter/balance/LoadBalance.java b/version3/src/main/java/part1/Client/serviceCenter/balance/LoadBalance.java deleted file mode 100644 index 03d3f7a..0000000 --- a/version3/src/main/java/part1/Client/serviceCenter/balance/LoadBalance.java +++ /dev/null @@ -1,15 +0,0 @@ -package part1.Client.serviceCenter.balance; - -import java.util.List; - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/19 21:00 - * 给服务地址列表,根据不同的负载均衡策略选择一个 - */ -public interface LoadBalance { - String balance(List addressList); - void addNode(String node) ; - void delNode(String node); -} \ No newline at end of file diff --git a/version3/src/main/java/part1/Client/serviceCenter/balance/impl/ConsistencyHashBalance.java b/version3/src/main/java/part1/Client/serviceCenter/balance/impl/ConsistencyHashBalance.java deleted file mode 100644 index 43b56af..0000000 --- a/version3/src/main/java/part1/Client/serviceCenter/balance/impl/ConsistencyHashBalance.java +++ /dev/null @@ -1,119 +0,0 @@ -package part1.Client.serviceCenter.balance.impl; - -import part1.Client.serviceCenter.balance.LoadBalance; - -import java.util.*; - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/19 21:16 - * 一致性哈希算法 负载均衡 - */ -public class ConsistencyHashBalance implements LoadBalance { - // 虚拟节点的个数 - private static final int VIRTUAL_NUM = 5; - - // 虚拟节点分配,key是hash值,value是虚拟节点服务器名称 - private SortedMap shards = new TreeMap(); - - // 真实节点列表 - private List realNodes = new LinkedList(); - - //模拟初始服务器 - private String[] servers =null; - - private void init(List serviceList) { - for (String server :serviceList) { - realNodes.add(server); - System.out.println("真实节点[" + server + "] 被添加"); - for (int i = 0; i < VIRTUAL_NUM; i++) { - String virtualNode = server + "&&VN" + i; - int hash = getHash(virtualNode); - shards.put(hash, virtualNode); - System.out.println("虚拟节点[" + virtualNode + "] hash:" + hash + ",被添加"); - } - } - } - /** - * 获取被分配的节点名 - * - * @param node - * @return - */ - public String getServer(String node,List serviceList) { - init(serviceList); - int hash = getHash(node); - Integer key = null; - SortedMap subMap = shards.tailMap(hash); - if (subMap.isEmpty()) { - key = shards.lastKey(); - } else { - key = subMap.firstKey(); - } - String virtualNode = shards.get(key); - return virtualNode.substring(0, virtualNode.indexOf("&&")); - } - - /** - * 添加节点 - * - * @param node - */ - public void addNode(String node) { - if (!realNodes.contains(node)) { - realNodes.add(node); - System.out.println("真实节点[" + node + "] 上线添加"); - for (int i = 0; i < VIRTUAL_NUM; i++) { - String virtualNode = node + "&&VN" + i; - int hash = getHash(virtualNode); - shards.put(hash, virtualNode); - System.out.println("虚拟节点[" + virtualNode + "] hash:" + hash + ",被添加"); - } - } - } - - /** - * 删除节点 - * - * @param node - */ - public void delNode(String node) { - if (realNodes.contains(node)) { - realNodes.remove(node); - System.out.println("真实节点[" + node + "] 下线移除"); - for (int i = 0; i < VIRTUAL_NUM; i++) { - String virtualNode = node + "&&VN" + i; - int hash = getHash(virtualNode); - shards.remove(hash); - System.out.println("虚拟节点[" + virtualNode + "] hash:" + hash + ",被移除"); - } - } - } - - /** - * FNV1_32_HASH算法 - */ - private static int getHash(String str) { - final int p = 16777619; - int hash = (int) 2166136261L; - for (int i = 0; i < str.length(); i++) - hash = (hash ^ str.charAt(i)) * p; - hash += hash << 13; - hash ^= hash >> 7; - hash += hash << 3; - hash ^= hash >> 17; - hash += hash << 5; - // 如果算出来的值为负数则取其绝对值 - if (hash < 0) - hash = Math.abs(hash); - return hash; - } - - @Override - public String balance(List addressList) { - String random= UUID.randomUUID().toString(); - return getServer(random,addressList); - } - -} diff --git a/version3/src/main/java/part1/Client/serviceCenter/balance/impl/RandomLoadBalance.java b/version3/src/main/java/part1/Client/serviceCenter/balance/impl/RandomLoadBalance.java deleted file mode 100644 index 9776d6b..0000000 --- a/version3/src/main/java/part1/Client/serviceCenter/balance/impl/RandomLoadBalance.java +++ /dev/null @@ -1,24 +0,0 @@ -package part1.Client.serviceCenter.balance.impl; - -import part1.Client.serviceCenter.balance.LoadBalance; - -import java.util.List; -import java.util.Random; - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/19 21:20 - * 随机 负载均衡 - */ -public class RandomLoadBalance implements LoadBalance { - @Override - public String balance(List addressList) { - Random random=new Random(); - int choose = random.nextInt(addressList.size()); - System.out.println("负载均衡选择了"+choose+"服务器"); - return null; - } - public void addNode(String node){} ; - public void delNode(String node){}; -} diff --git a/version3/src/main/java/part1/Client/serviceCenter/balance/impl/RoundLoadBalance.java b/version3/src/main/java/part1/Client/serviceCenter/balance/impl/RoundLoadBalance.java deleted file mode 100644 index 9f90d59..0000000 --- a/version3/src/main/java/part1/Client/serviceCenter/balance/impl/RoundLoadBalance.java +++ /dev/null @@ -1,24 +0,0 @@ -package part1.Client.serviceCenter.balance.impl; - -import part1.Client.serviceCenter.balance.LoadBalance; - -import java.util.List; - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/19 21:21 - * 轮询 负载均衡 - */ -public class RoundLoadBalance implements LoadBalance { - private int choose=-1; - @Override - public String balance(List addressList) { - choose++; - choose=choose%addressList.size(); - System.out.println("负载均衡选择了"+choose+"服务器"); - return addressList.get(choose); - } - public void addNode(String node) {}; - public void delNode(String node){}; -} diff --git a/version3/src/main/java/part1/Server/TestServer.java b/version3/src/main/java/part1/Server/TestServer.java deleted file mode 100644 index c91be84..0000000 --- a/version3/src/main/java/part1/Server/TestServer.java +++ /dev/null @@ -1,27 +0,0 @@ -package part1.Server; - - -import part1.Server.server.impl.NettyRPCRPCServer; -import part1.common.service.Impl.UserServiceImpl; -import part1.Server.provider.ServiceProvider; -import part1.Server.server.RpcServer; -import part1.common.service.UserService; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/11 19:39 - */ - -public class TestServer { - public static void main(String[] args) throws InterruptedException { - UserService userService=new UserServiceImpl(); - - ServiceProvider serviceProvider=new ServiceProvider("127.0.0.1",9999); - - serviceProvider.provideServiceInterface(userService); - - RpcServer rpcServer=new NettyRPCRPCServer(serviceProvider); - rpcServer.start(9999); - } -} diff --git a/version3/src/main/java/part1/Server/netty/handler/NettyRPCServerHandler.java b/version3/src/main/java/part1/Server/netty/handler/NettyRPCServerHandler.java deleted file mode 100644 index ab63437..0000000 --- a/version3/src/main/java/part1/Server/netty/handler/NettyRPCServerHandler.java +++ /dev/null @@ -1,51 +0,0 @@ -package part1.Server.netty.handler; - -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.SimpleChannelInboundHandler; -import lombok.AllArgsConstructor; -import part1.common.Message.RpcRequest; -import part1.common.Message.RpcResponse; -import part1.Server.provider.ServiceProvider; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/26 16:40 - * 因为是服务器端,我们知道接受到请求格式是RPCRequest - * Object类型也行,强制转型就行 - */ -@AllArgsConstructor -public class NettyRPCServerHandler extends SimpleChannelInboundHandler { - private ServiceProvider serviceProvider; - @Override - protected void channelRead0(ChannelHandlerContext ctx, RpcRequest request) throws Exception { - RpcResponse response = getResponse(request); - ctx.writeAndFlush(response); - ctx.close(); - } - @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { - cause.printStackTrace(); - ctx.close(); - } - private RpcResponse getResponse(RpcRequest rpcRequest){ - //得到服务名 - String interfaceName=rpcRequest.getInterfaceName(); - //得到服务端相应服务实现类 - Object service = serviceProvider.getService(interfaceName); - //反射调用方法 - Method method=null; - try { - method= service.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParamsType()); - Object invoke=method.invoke(service,rpcRequest.getParams()); - return RpcResponse.sussess(invoke); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - e.printStackTrace(); - System.out.println("方法执行错误"); - return RpcResponse.fail(); - } - } -} diff --git a/version3/src/main/java/part1/Server/netty/nettyInitializer/NettyServerInitializer.java b/version3/src/main/java/part1/Server/netty/nettyInitializer/NettyServerInitializer.java deleted file mode 100644 index f19c612..0000000 --- a/version3/src/main/java/part1/Server/netty/nettyInitializer/NettyServerInitializer.java +++ /dev/null @@ -1,30 +0,0 @@ -package part1.Server.netty.nettyInitializer; - - -import io.netty.channel.ChannelInitializer; -import io.netty.channel.ChannelPipeline; -import io.netty.channel.socket.SocketChannel; -import lombok.AllArgsConstructor; -import part1.common.serializer.myCode.MyEncoder; -import part1.common.serializer.mySerializer.JsonSerializer; -import part1.Server.netty.handler.NettyRPCServerHandler; -import part1.Server.provider.ServiceProvider; -import part1.common.serializer.myCode.MyDecoder; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/26 16:15 - */ -@AllArgsConstructor -public class NettyServerInitializer extends ChannelInitializer { - private ServiceProvider serviceProvider; - @Override - protected void initChannel(SocketChannel ch) throws Exception { - ChannelPipeline pipeline = ch.pipeline(); - //使用自定义的编/解码器 - pipeline.addLast(new MyEncoder(new JsonSerializer())); - pipeline.addLast(new MyDecoder()); - pipeline.addLast(new NettyRPCServerHandler(serviceProvider)); - } -} diff --git a/version3/src/main/java/part1/Server/provider/ServiceProvider.java b/version3/src/main/java/part1/Server/provider/ServiceProvider.java deleted file mode 100644 index f7355dc..0000000 --- a/version3/src/main/java/part1/Server/provider/ServiceProvider.java +++ /dev/null @@ -1,47 +0,0 @@ -package part1.Server.provider; - -import part1.Server.serviceRegister.ServiceRegister; -import part1.Server.serviceRegister.impl.ZKServiceRegister; - -import java.net.InetSocketAddress; -import java.util.HashMap; -import java.util.Map; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/16 17:35 - */ -public class ServiceProvider { - private Map interfaceProvider; - - private int port; - private String host; - //注册服务类 - private ServiceRegister serviceRegister; - - public ServiceProvider(String host,int port){ - //需要传入服务端自身的网络地址 - this.host=host; - this.port=port; - this.interfaceProvider=new HashMap<>(); - this.serviceRegister=new ZKServiceRegister(); - } - - public void provideServiceInterface(Object service){ - String serviceName=service.getClass().getName(); - Class[] interfaceName=service.getClass().getInterfaces(); - - for (Class clazz:interfaceName){ - //本机的映射表 - interfaceProvider.put(clazz.getName(),service); - //在注册中心注册服务 - serviceRegister.register(clazz.getName(),new InetSocketAddress(host,port)); - } - } - - public Object getService(String interfaceName){ - return interfaceProvider.get(interfaceName); - } - -} diff --git a/version3/src/main/java/part1/Server/server/RpcServer.java b/version3/src/main/java/part1/Server/server/RpcServer.java deleted file mode 100644 index 7ed9584..0000000 --- a/version3/src/main/java/part1/Server/server/RpcServer.java +++ /dev/null @@ -1,11 +0,0 @@ -package part1.Server.server; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/12 11:26 - */ -public interface RpcServer { - void start(int port); - void stop(); -} diff --git a/version3/src/main/java/part1/Server/server/impl/NettyRPCRPCServer.java b/version3/src/main/java/part1/Server/server/impl/NettyRPCRPCServer.java deleted file mode 100644 index 514b857..0000000 --- a/version3/src/main/java/part1/Server/server/impl/NettyRPCRPCServer.java +++ /dev/null @@ -1,48 +0,0 @@ -package part1.Server.server.impl; - -import io.netty.bootstrap.ServerBootstrap; -import io.netty.channel.ChannelFuture; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.nio.NioServerSocketChannel; -import lombok.AllArgsConstructor; -import part1.Server.netty.nettyInitializer.NettyServerInitializer; -import part1.Server.provider.ServiceProvider; -import part1.Server.server.RpcServer; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/26 14:01 - */ -@AllArgsConstructor -public class NettyRPCRPCServer implements RpcServer { - private ServiceProvider serviceProvider; - @Override - public void start(int port) { - // netty 服务线程组boss负责建立连接, work负责具体的请求 - NioEventLoopGroup bossGroup = new NioEventLoopGroup(); - NioEventLoopGroup workGroup = new NioEventLoopGroup(); - System.out.println("netty服务端启动了"); - try { - //启动netty服务器 - ServerBootstrap serverBootstrap = new ServerBootstrap(); - //初始化 - serverBootstrap.group(bossGroup,workGroup).channel(NioServerSocketChannel.class) - .childHandler(new NettyServerInitializer(serviceProvider)); - //同步堵塞 - ChannelFuture channelFuture=serverBootstrap.bind(port).sync(); - //死循环监听 - channelFuture.channel().closeFuture().sync(); - }catch (InterruptedException e){ - e.printStackTrace(); - }finally { - bossGroup.shutdownGracefully(); - workGroup.shutdownGracefully(); - } - } - - @Override - public void stop() { - - } -} diff --git a/version3/src/main/java/part1/Server/server/impl/SimpleRPCRPCServer.java b/version3/src/main/java/part1/Server/server/impl/SimpleRPCRPCServer.java deleted file mode 100644 index 917c8a2..0000000 --- a/version3/src/main/java/part1/Server/server/impl/SimpleRPCRPCServer.java +++ /dev/null @@ -1,39 +0,0 @@ -package part1.Server.server.impl; - - -import lombok.AllArgsConstructor; -import part1.Server.provider.ServiceProvider; -import part1.Server.server.RpcServer; -import part1.Server.server.work.WorkThread; - -import java.io.IOException; -import java.net.ServerSocket; -import java.net.Socket; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/12 11:37 - */ -@AllArgsConstructor -public class SimpleRPCRPCServer implements RpcServer { - private ServiceProvider serviceProvide; - @Override - public void start(int port) { - try { - ServerSocket serverSocket=new ServerSocket(port); - System.out.println("服务器启动了"); - while (true) { - Socket socket = serverSocket.accept(); - new Thread(new WorkThread(socket,serviceProvide)).start(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Override - public void stop() { - - } -} diff --git a/version3/src/main/java/part1/Server/server/work/WorkThread.java b/version3/src/main/java/part1/Server/server/work/WorkThread.java deleted file mode 100644 index 50fbeca..0000000 --- a/version3/src/main/java/part1/Server/server/work/WorkThread.java +++ /dev/null @@ -1,58 +0,0 @@ -package part1.Server.server.work; - - -import lombok.AllArgsConstructor; -import part1.common.Message.RpcResponse; -import part1.Server.provider.ServiceProvider; -import part1.common.Message.RpcRequest; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.Socket; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/14 17:39 - */ -@AllArgsConstructor -public class WorkThread implements Runnable{ - private Socket socket; - private ServiceProvider serviceProvide; - @Override - public void run() { - try { - ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream()); - ObjectInputStream ois=new ObjectInputStream(socket.getInputStream()); - //读取客户端传过来的request - RpcRequest rpcRequest = (RpcRequest) ois.readObject(); - //反射调用服务方法获取返回值 - RpcResponse rpcResponse=getResponse(rpcRequest); - //向客户端写入response - oos.writeObject(rpcResponse); - oos.flush(); - } catch (IOException | ClassNotFoundException e) { - e.printStackTrace(); - } - } - private RpcResponse getResponse(RpcRequest rpcRequest){ - //得到服务名 - String interfaceName=rpcRequest.getInterfaceName(); - //得到服务端相应服务实现类 - Object service = serviceProvide.getService(interfaceName); - //反射调用方法 - Method method=null; - try { - method= service.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParamsType()); - Object invoke=method.invoke(service,rpcRequest.getParams()); - return RpcResponse.sussess(invoke); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - e.printStackTrace(); - System.out.println("方法执行错误"); - return RpcResponse.fail(); - } - } -} diff --git a/version3/src/main/java/part1/Server/serviceRegister/ServiceRegister.java b/version3/src/main/java/part1/Server/serviceRegister/ServiceRegister.java deleted file mode 100644 index 54c52b1..0000000 --- a/version3/src/main/java/part1/Server/serviceRegister/ServiceRegister.java +++ /dev/null @@ -1,15 +0,0 @@ -package part1.Server.serviceRegister; - -import java.net.InetSocketAddress; - -/** - * @author wxx - * @version 1.0 - * @create 2024/5/3 16:58 - */ -// 服务注册接口 -public interface ServiceRegister { - // 注册:保存服务与地址。 - void register(String serviceName, InetSocketAddress serviceAddress); - -} diff --git a/version3/src/main/java/part1/Server/serviceRegister/impl/ZKServiceRegister.java b/version3/src/main/java/part1/Server/serviceRegister/impl/ZKServiceRegister.java deleted file mode 100644 index d569338..0000000 --- a/version3/src/main/java/part1/Server/serviceRegister/impl/ZKServiceRegister.java +++ /dev/null @@ -1,62 +0,0 @@ -package part1.Server.serviceRegister.impl; - -import org.apache.curator.RetryPolicy; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.retry.ExponentialBackoffRetry; -import org.apache.zookeeper.CreateMode; -import part1.Server.serviceRegister.ServiceRegister; - -import java.net.InetSocketAddress; -/** - * @author wxx - * @version 1.0 - * @create 2024/5/3 17:28 - */ -public class ZKServiceRegister implements ServiceRegister { - // curator 提供的zookeeper客户端 - private CuratorFramework client; - //zookeeper根路径节点 - private static final String ROOT_PATH = "MyRPC"; - - //负责zookeeper客户端的初始化,并与zookeeper服务端进行连接 - public ZKServiceRegister(){ - // 指数时间重试 - RetryPolicy policy = new ExponentialBackoffRetry(1000, 3); - // zookeeper的地址固定,不管是服务提供者还是,消费者都要与之建立连接 - // sessionTimeoutMs 与 zoo.cfg中的tickTime 有关系, - // zk还会根据minSessionTimeout与maxSessionTimeout两个参数重新调整最后的超时值。默认分别为tickTime 的2倍和20倍 - // 使用心跳监听状态 - this.client = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181") - .sessionTimeoutMs(40000).retryPolicy(policy).namespace(ROOT_PATH).build(); - this.client.start(); - System.out.println("zookeeper 连接成功"); - } - //注册服务到注册中心 - @Override - public void register(String serviceName, InetSocketAddress serviceAddress) { - try { - // serviceName创建成永久节点,服务提供者下线时,不删服务名,只删地址 - if(client.checkExists().forPath("/" + serviceName) == null){ - client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/" + serviceName); - } - // 路径地址,一个/代表一个节点 - String path = "/" + serviceName +"/"+ getServiceAddress(serviceAddress); - // 临时节点,服务器下线就删除节点 - client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path); - } catch (Exception e) { - System.out.println("此服务已存在"); - } - } - // 地址 -> XXX.XXX.XXX.XXX:port 字符串 - private String getServiceAddress(InetSocketAddress serverAddress) { - return serverAddress.getHostName() + - ":" + - serverAddress.getPort(); - } - // 字符串解析为地址 - private InetSocketAddress parseAddress(String address) { - String[] result = address.split(":"); - return new InetSocketAddress(result[0], Integer.parseInt(result[1])); - } -} diff --git a/version3/src/main/java/part1/common/Message/MessageType.java b/version3/src/main/java/part1/common/Message/MessageType.java deleted file mode 100644 index ebbcc83..0000000 --- a/version3/src/main/java/part1/common/Message/MessageType.java +++ /dev/null @@ -1,17 +0,0 @@ -package part1.common.Message; - -import lombok.AllArgsConstructor; - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/2 22:29 - */ -@AllArgsConstructor -public enum MessageType { - REQUEST(0),RESPONSE(1); - private int code; - public int getCode(){ - return code; - } -} \ No newline at end of file diff --git a/version3/src/main/java/part1/common/Message/RpcRequest.java b/version3/src/main/java/part1/common/Message/RpcRequest.java deleted file mode 100644 index 2642f38..0000000 --- a/version3/src/main/java/part1/common/Message/RpcRequest.java +++ /dev/null @@ -1,29 +0,0 @@ -package part1.common.Message; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.io.Serializable; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/1 18:30 - * 定义发送的消息格式 - */ -@NoArgsConstructor -@AllArgsConstructor -@Data -@Builder -public class RpcRequest implements Serializable { - //服务类名,客户端只知道接口 - private String interfaceName; - //调用的方法名 - private String methodName; - //参数列表 - private Object[] params; - //参数类型 - private Class[] paramsType; -} diff --git a/version3/src/main/java/part1/common/Message/RpcResponse.java b/version3/src/main/java/part1/common/Message/RpcResponse.java deleted file mode 100644 index 7a44b45..0000000 --- a/version3/src/main/java/part1/common/Message/RpcResponse.java +++ /dev/null @@ -1,35 +0,0 @@ -package part1.common.Message; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.io.Serializable; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/1 19:18 - */ -@NoArgsConstructor -@AllArgsConstructor -@Data -@Builder -public class RpcResponse implements Serializable { - //状态信息 - private int code; - private String message; - //更新:加入传输数据的类型,以便在自定义序列化器中解析 - private Class dataType; - //具体数据 - private Object data; - - public static RpcResponse sussess(Object data){ - return RpcResponse.builder().code(200).dataType(data.getClass()).data(data).build(); - } - public static RpcResponse fail(){ - return RpcResponse.builder().code(500).message("服务器发生错误").build(); - } -} - diff --git a/version3/src/main/java/part1/common/pojo/User.java b/version3/src/main/java/part1/common/pojo/User.java deleted file mode 100644 index d7cef8c..0000000 --- a/version3/src/main/java/part1/common/pojo/User.java +++ /dev/null @@ -1,25 +0,0 @@ -package part1.common.pojo; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.io.Serializable; - -/** - * @author wxx - * @version 1.0 - * @create 2024/1/28 17:50 - */ -@Builder -@Data -@NoArgsConstructor -@AllArgsConstructor -public class User implements Serializable { - // 客户端和服务端共有的 - private Integer id; - private String userName; - private Boolean sex; -} - diff --git a/version3/src/main/java/part1/common/serializer/myCode/MyDecoder.java b/version3/src/main/java/part1/common/serializer/myCode/MyDecoder.java deleted file mode 100644 index 78ed394..0000000 --- a/version3/src/main/java/part1/common/serializer/myCode/MyDecoder.java +++ /dev/null @@ -1,41 +0,0 @@ -package part1.common.serializer.myCode; - -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.ByteToMessageDecoder; -import part1.common.Message.MessageType; -import part1.common.serializer.mySerializer.Serializer; - -import java.util.List; - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/2 22:24 - * 按照自定义的消息格式解码数据 - */ -public class MyDecoder extends ByteToMessageDecoder { - @Override - protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List out) throws Exception { - //1.读取消息类型 - short messageType = in.readShort(); - // 现在还只支持request与response请求 - if(messageType != MessageType.REQUEST.getCode() && - messageType != MessageType.RESPONSE.getCode()){ - System.out.println("暂不支持此种数据"); - return; - } - //2.读取序列化的方式&类型 - short serializerType = in.readShort(); - Serializer serializer = Serializer.getSerializerByCode(serializerType); - if(serializer == null) - throw new RuntimeException("不存在对应的序列化器"); - //3.读取序列化数组长度 - int length = in.readInt(); - //4.读取序列化数组 - byte[] bytes=new byte[length]; - in.readBytes(bytes); - Object deserialize= serializer.deserialize(bytes, messageType); - out.add(deserialize); - } -} diff --git a/version3/src/main/java/part1/common/serializer/myCode/MyEncoder.java b/version3/src/main/java/part1/common/serializer/myCode/MyEncoder.java deleted file mode 100644 index 7ce0fd4..0000000 --- a/version3/src/main/java/part1/common/serializer/myCode/MyEncoder.java +++ /dev/null @@ -1,41 +0,0 @@ -package part1.common.serializer.myCode; - -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.MessageToByteEncoder; -import lombok.AllArgsConstructor; -import part1.common.Message.MessageType; -import part1.common.Message.RpcRequest; -import part1.common.Message.RpcResponse; -import part1.common.serializer.mySerializer.Serializer; - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/2 22:24 - * 依次按照自定义的消息格式写入,传入的数据为request或者response - * 需要持有一个serialize器,负责将传入的对象序列化成字节数组 - */ -@AllArgsConstructor -public class MyEncoder extends MessageToByteEncoder { - private Serializer serializer; - @Override - protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception { - System.out.println(msg.getClass()); - //1.写入消息类型 - if(msg instanceof RpcRequest){ - out.writeShort(MessageType.REQUEST.getCode()); - } - else if(msg instanceof RpcResponse){ - out.writeShort(MessageType.RESPONSE.getCode()); - } - //2.写入序列化方式 - out.writeShort(serializer.getType()); - //得到序列化数组 - byte[] serializeBytes = serializer.serialize(msg); - //3.写入长度 - out.writeInt(serializeBytes.length); - //4.写入序列化数组 - out.writeBytes(serializeBytes); - } -} diff --git a/version3/src/main/java/part1/common/serializer/mySerializer/JsonSerializer.java b/version3/src/main/java/part1/common/serializer/mySerializer/JsonSerializer.java deleted file mode 100644 index 4557f3c..0000000 --- a/version3/src/main/java/part1/common/serializer/mySerializer/JsonSerializer.java +++ /dev/null @@ -1,65 +0,0 @@ -package part1.common.serializer.mySerializer; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import part1.common.Message.RpcResponse; -import part1.common.Message.RpcRequest; - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/2 22:31 - */ -public class JsonSerializer implements Serializer { - @Override - public byte[] serialize(Object obj) { - byte[] bytes = JSONObject.toJSONBytes(obj); - return bytes; - } - - @Override - public Object deserialize(byte[] bytes, int messageType) { - Object obj = null; - // 传输的消息分为request与response - switch (messageType){ - case 0: - RpcRequest request = JSON.parseObject(bytes, RpcRequest.class); - Object[] objects = new Object[request.getParams().length]; - // 把json字串转化成对应的对象, fastjson可以读出基本数据类型,不用转化 - // 对转换后的request中的params属性逐个进行类型判断 - for(int i = 0; i < objects.length; i++){ - Class paramsType = request.getParamsType()[i]; - //判断每个对象类型是否和paramsTypes中的一致 - if (!paramsType.isAssignableFrom(request.getParams()[i].getClass())){ - //如果不一致,就行进行类型转换 - objects[i] = JSONObject.toJavaObject((JSONObject) request.getParams()[i],request.getParamsType()[i]); - }else{ - //如果一致就直接赋给objects[i] - objects[i] = request.getParams()[i]; - } - } - request.setParams(objects); - obj = request; - break; - case 1: - RpcResponse response = JSON.parseObject(bytes, RpcResponse.class); - Class dataType = response.getDataType(); - //判断转化后的response对象中的data的类型是否正确 - if(! dataType.isAssignableFrom(response.getData().getClass())){ - response.setData(JSONObject.toJavaObject((JSONObject) response.getData(),dataType)); - } - obj = response; - break; - default: - System.out.println("暂时不支持此种消息"); - throw new RuntimeException(); - } - return obj; - } - - //1 代表json序列化方式 - @Override - public int getType() { - return 1; - } -} diff --git a/version3/src/main/java/part1/common/serializer/mySerializer/ObjectSerializer.java b/version3/src/main/java/part1/common/serializer/mySerializer/ObjectSerializer.java deleted file mode 100644 index 3eec03c..0000000 --- a/version3/src/main/java/part1/common/serializer/mySerializer/ObjectSerializer.java +++ /dev/null @@ -1,54 +0,0 @@ -package part1.common.serializer.mySerializer; - -import java.io.*; - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/2 22:36 - */ -public class ObjectSerializer implements Serializer { - //利用Java io 对象 -》字节数组 - @Override - public byte[] serialize(Object obj) { - byte[] bytes=null; - ByteArrayOutputStream bos=new ByteArrayOutputStream(); - try { - //是一个对象输出流,用于将 Java 对象序列化为字节流,并将其连接到bos上 - ObjectOutputStream oos = new ObjectOutputStream(bos); - oos.writeObject(obj); - //刷新 ObjectOutputStream,确保所有缓冲区中的数据都被写入到底层流中。 - oos.flush(); - //将bos其内部缓冲区中的数据转换为字节数组 - bytes = bos.toByteArray(); - oos.close(); - bos.close(); - } catch (IOException e) { - e.printStackTrace(); - } - return bytes; - } - - //字节数组 -》对象 - @Override - public Object deserialize(byte[] bytes, int messageType) { - Object obj = null; - ByteArrayInputStream bis = new ByteArrayInputStream(bytes); - try { - ObjectInputStream ois = new ObjectInputStream(bis); - obj = ois.readObject(); - ois.close(); - bis.close(); - } catch (IOException | ClassNotFoundException e) { - e.printStackTrace(); - } - return obj; - } - - //0 代表Java 原生序列器 - @Override - public int getType() { - return 0; - } -} - diff --git a/version3/src/main/java/part1/common/serializer/mySerializer/Serializer.java b/version3/src/main/java/part1/common/serializer/mySerializer/Serializer.java deleted file mode 100644 index e0829d0..0000000 --- a/version3/src/main/java/part1/common/serializer/mySerializer/Serializer.java +++ /dev/null @@ -1,29 +0,0 @@ -package part1.common.serializer.mySerializer; - - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/2 22:31 - */ -public interface Serializer { - // 把对象序列化成字节数组 - byte[] serialize(Object obj); - // 从字节数组反序列化成消息, 使用java自带序列化方式不用messageType也能得到相应的对象(序列化字节数组里包含类信息) - // 其它方式需指定消息格式,再根据message转化成相应的对象 - Object deserialize(byte[] bytes, int messageType); - // 返回使用的序列器,是哪个 - // 0:java自带序列化方式, 1: json序列化方式 - int getType(); - // 根据序号取出序列化器,暂时有两种实现方式,需要其它方式,实现这个接口即可 - static Serializer getSerializerByCode(int code){ - switch (code){ - case 0: - return new ObjectSerializer(); - case 1: - return new JsonSerializer(); - default: - return null; - } - } -} diff --git a/version3/src/main/java/part1/common/service/Impl/UserServiceImpl.java b/version3/src/main/java/part1/common/service/Impl/UserServiceImpl.java deleted file mode 100644 index 373243b..0000000 --- a/version3/src/main/java/part1/common/service/Impl/UserServiceImpl.java +++ /dev/null @@ -1,32 +0,0 @@ -package part1.common.service.Impl; - - -import part1.common.pojo.User; -import part1.common.service.UserService; - -import java.util.Random; -import java.util.UUID; - -/** - * @author wxx - * @version 1.0 - * @create 2024/1/28 16:28 - */ -public class UserServiceImpl implements UserService { - @Override - public User getUserByUserId(Integer id) { - System.out.println("客户端查询了"+id+"的用户"); - // 模拟从数据库中取用户的行为 - Random random = new Random(); - User user = User.builder().userName(UUID.randomUUID().toString()) - .id(id) - .sex(random.nextBoolean()).build(); - return user; - } - - @Override - public Integer insertUserId(User user) { - System.out.println("插入数据成功"+user.getUserName()); - return user.getId(); - } -} \ No newline at end of file diff --git a/version3/src/main/java/part1/common/service/UserService.java b/version3/src/main/java/part1/common/service/UserService.java deleted file mode 100644 index 0e539bd..0000000 --- a/version3/src/main/java/part1/common/service/UserService.java +++ /dev/null @@ -1,16 +0,0 @@ -package part1.common.service; - - -import part1.common.pojo.User; - -/** - * @author wxx - * @version 1.0 - * @create 2024/1/28 16:27 - */ -public interface UserService { - // 客户端通过这个接口调用服务端的实现类 - User getUserByUserId(Integer id); - //新增一个功能 - Integer insertUserId(User user); -} diff --git a/version3/src/main/java/part2/Client/TestClient.java b/version3/src/main/java/part2/Client/TestClient.java deleted file mode 100644 index f679b83..0000000 --- a/version3/src/main/java/part2/Client/TestClient.java +++ /dev/null @@ -1,28 +0,0 @@ -package part2.Client; - - -import part2.Client.proxy.ClientProxy; -import part2.common.pojo.User; -import part2.common.service.UserService; - - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/6 18:39 - */ - -public class TestClient { - public static void main(String[] args) throws InterruptedException { - ClientProxy clientProxy=new ClientProxy(); - //ClientProxy clientProxy=new proxy.Client.part1.ClientProxy("127.0.0.1",9999,0); - UserService proxy=clientProxy.getProxy(UserService.class); - - User user = proxy.getUserByUserId(1); - System.out.println("从服务端得到的user="+user.toString()); - - User u=User.builder().id(100).userName("wxx").sex(true).build(); - Integer id = proxy.insertUserId(u); - System.out.println("向服务端插入user的id"+id); - } -} diff --git a/version3/src/main/java/part2/Client/cache/serviceCache.java b/version3/src/main/java/part2/Client/cache/serviceCache.java deleted file mode 100644 index f6c7106..0000000 --- a/version3/src/main/java/part2/Client/cache/serviceCache.java +++ /dev/null @@ -1,54 +0,0 @@ -package part2.Client.cache; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/4 0:57 - */ -public class serviceCache { - //key: serviceName 服务名 - //value: addressList 服务提供者列表 - private static Map> cache=new HashMap<>(); - - //添加服务 - public void addServcieToCache(String serviceName,String address){ - if(cache.containsKey(serviceName)){ - List addressList = cache.get(serviceName); - addressList.add(address); - System.out.println("将name为"+serviceName+"和地址为"+address+"的服务添加到本地缓存中"); - }else { - List addressList=new ArrayList<>(); - addressList.add(address); - cache.put(serviceName,addressList); - } - } - //修改服务地址 - public void replaceServiceAddress(String serviceName,String oldAddress,String newAddress){ - if(cache.containsKey(serviceName)){ - List addressList=cache.get(serviceName); - addressList.remove(oldAddress); - addressList.add(newAddress); - }else { - System.out.println("修改失败,服务不存在"); - } - } - //从缓存中取服务地址列表 - public List getServiceListFromCache(String serviceName){ - if(!cache.containsKey(serviceName)) { - return null; - } - return cache.get(serviceName); - } - - //从缓存中删除服务地址 - public void delete(String serviceName,String address){ - List addressList = cache.get(serviceName); - addressList.remove(address); - System.out.println("将name为"+serviceName+"和地址为"+address+"的服务从本地缓存中删除"); - } -} diff --git a/version3/src/main/java/part2/Client/netty/handler/NettyClientHandler.java b/version3/src/main/java/part2/Client/netty/handler/NettyClientHandler.java deleted file mode 100644 index 95eaf28..0000000 --- a/version3/src/main/java/part2/Client/netty/handler/NettyClientHandler.java +++ /dev/null @@ -1,27 +0,0 @@ -package part2.Client.netty.handler; - -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.SimpleChannelInboundHandler; -import io.netty.util.AttributeKey; -import part2.common.Message.RpcResponse; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/26 17:29 - */ -public class NettyClientHandler extends SimpleChannelInboundHandler { - @Override - protected void channelRead0(ChannelHandlerContext ctx, RpcResponse response) throws Exception { - // 接收到response, 给channel设计别名,让sendRequest里读取response - AttributeKey key = AttributeKey.valueOf("RPCResponse"); - ctx.channel().attr(key).set(response); - ctx.channel().close(); - } - - @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { - cause.printStackTrace(); - ctx.close(); - } -} diff --git a/version3/src/main/java/part2/Client/netty/nettyInitializer/NettyClientInitializer.java b/version3/src/main/java/part2/Client/netty/nettyInitializer/NettyClientInitializer.java deleted file mode 100644 index 175c729..0000000 --- a/version3/src/main/java/part2/Client/netty/nettyInitializer/NettyClientInitializer.java +++ /dev/null @@ -1,26 +0,0 @@ -package part2.Client.netty.nettyInitializer; - - -import io.netty.channel.ChannelInitializer; -import io.netty.channel.ChannelPipeline; -import io.netty.channel.socket.SocketChannel; -import part2.Client.netty.handler.NettyClientHandler; -import part2.common.serializer.myCode.MyDecoder; -import part2.common.serializer.myCode.MyEncoder; -import part2.common.serializer.mySerializer.JsonSerializer; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/26 17:26 - */ -public class NettyClientInitializer extends ChannelInitializer { - @Override - protected void initChannel(SocketChannel ch) throws Exception { - ChannelPipeline pipeline = ch.pipeline(); - //使用自定义的编/解码器 - pipeline.addLast(new MyEncoder(new JsonSerializer())); - pipeline.addLast(new MyDecoder()); - pipeline.addLast(new NettyClientHandler()); - } -} diff --git a/version3/src/main/java/part2/Client/proxy/ClientProxy.java b/version3/src/main/java/part2/Client/proxy/ClientProxy.java deleted file mode 100644 index 289c7fc..0000000 --- a/version3/src/main/java/part2/Client/proxy/ClientProxy.java +++ /dev/null @@ -1,55 +0,0 @@ -package part2.Client.proxy; - - -import part2.Client.retry.guavaRetry; -import part2.Client.rpcClient.RpcClient; -import part2.Client.rpcClient.impl.NettyRpcClient; -import part2.Client.serviceCenter.ServiceCenter; -import part2.Client.serviceCenter.ZKServiceCenter; -import part2.common.Message.RpcRequest; -import part2.common.Message.RpcResponse; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/6 16:49 - */ -public class ClientProxy implements InvocationHandler { - //传入参数service接口的class对象,反射封装成一个request - - private RpcClient rpcClient; - private ServiceCenter serviceCenter; - public ClientProxy() throws InterruptedException { - serviceCenter=new ZKServiceCenter(); - rpcClient=new NettyRpcClient(serviceCenter); - } - - //jdk动态代理,每一次代理对象调用方法,都会经过此方法增强(反射获取request对象,socket发送到服务端) - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - //构建request - RpcRequest request=RpcRequest.builder() - .interfaceName(method.getDeclaringClass().getName()) - .methodName(method.getName()) - .params(args).paramsType(method.getParameterTypes()).build(); - //数据传输 - RpcResponse response; - //后续添加逻辑:为保持幂等性,只对白名单上的服务进行重试 - if (serviceCenter.checkRetry(request.getInterfaceName())){ - //调用retry框架进行重试操作 - response=new guavaRetry().sendServiceWithRetry(request,rpcClient); - }else { - //只调用一次 - response= rpcClient.sendRequest(request); - } - return response.getData(); - } - public T getProxy(Class clazz){ - Object o = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, this); - return (T)o; - } -} diff --git a/version3/src/main/java/part2/Client/retry/guavaRetry.java b/version3/src/main/java/part2/Client/retry/guavaRetry.java deleted file mode 100644 index 2fc5bfd..0000000 --- a/version3/src/main/java/part2/Client/retry/guavaRetry.java +++ /dev/null @@ -1,43 +0,0 @@ -package part2.Client.retry; - -import com.github.rholder.retry.*; -import part2.Client.rpcClient.RpcClient; -import part2.common.Message.RpcRequest; -import part2.common.Message.RpcResponse; - -import java.util.Objects; -import java.util.concurrent.TimeUnit; - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/20 19:28 - */ -public class guavaRetry { - private RpcClient rpcClient; - public RpcResponse sendServiceWithRetry(RpcRequest request, RpcClient rpcClient) { - this.rpcClient=rpcClient; - Retryer retryer = RetryerBuilder.newBuilder() - //无论出现什么异常,都进行重试 - .retryIfException() - //返回结果为 error时进行重试 - .retryIfResult(response -> Objects.equals(response.getCode(), 500)) - //重试等待策略:等待 2s 后再进行重试 - .withWaitStrategy(WaitStrategies.fixedWait(2, TimeUnit.SECONDS)) - //重试停止策略:重试达到 3 次 - .withStopStrategy(StopStrategies.stopAfterAttempt(3)) - .withRetryListener(new RetryListener() { - @Override - public void onRetry(Attempt attempt) { - System.out.println("RetryListener: 第" + attempt.getAttemptNumber() + "次调用"); - } - }) - .build(); - try { - return retryer.call(() -> rpcClient.sendRequest(request)); - } catch (Exception e) { - e.printStackTrace(); - } - return RpcResponse.fail(); - } -} \ No newline at end of file diff --git a/version3/src/main/java/part2/Client/rpcClient/RpcClient.java b/version3/src/main/java/part2/Client/rpcClient/RpcClient.java deleted file mode 100644 index 21690b1..0000000 --- a/version3/src/main/java/part2/Client/rpcClient/RpcClient.java +++ /dev/null @@ -1,15 +0,0 @@ -package part2.Client.rpcClient; - -import part2.common.Message.RpcRequest; -import part2.common.Message.RpcResponse; - -/** - * @author wxx - * @version 1.0 - * @create 2024/5/2 18:55 - */ -public interface RpcClient { - - //定义底层通信的方法 - RpcResponse sendRequest(RpcRequest request); -} diff --git a/version3/src/main/java/part2/Client/rpcClient/impl/NettyRpcClient.java b/version3/src/main/java/part2/Client/rpcClient/impl/NettyRpcClient.java deleted file mode 100644 index 1f5d026..0000000 --- a/version3/src/main/java/part2/Client/rpcClient/impl/NettyRpcClient.java +++ /dev/null @@ -1,68 +0,0 @@ -package part2.Client.rpcClient.impl; - -import io.netty.bootstrap.Bootstrap; -import io.netty.channel.Channel; -import io.netty.channel.ChannelFuture; -import io.netty.channel.EventLoopGroup; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.nio.NioSocketChannel; -import io.netty.util.AttributeKey; -import part2.Client.netty.nettyInitializer.NettyClientInitializer; -import part2.Client.rpcClient.RpcClient; -import part2.Client.serviceCenter.ServiceCenter; -import part2.Client.serviceCenter.ZKServiceCenter; -import part2.common.Message.RpcRequest; -import part2.common.Message.RpcResponse; - -import java.net.InetSocketAddress; - -/** - * @author wxx - * @version 1.0 - * @create 2024/5/2 19:40 - */ -public class NettyRpcClient implements RpcClient { - - private static final Bootstrap bootstrap; - private static final EventLoopGroup eventLoopGroup; - - private ServiceCenter serviceCenter; - public NettyRpcClient(ServiceCenter serviceCenter) throws InterruptedException { - this.serviceCenter=serviceCenter; - } - - //netty客户端初始化 - static { - eventLoopGroup = new NioEventLoopGroup(); - bootstrap = new Bootstrap(); - bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class) - .handler(new NettyClientInitializer()); - } - @Override - public RpcResponse sendRequest(RpcRequest request) { - //从注册中心获取host,post - InetSocketAddress address = serviceCenter.serviceDiscovery(request.getInterfaceName()); - String host = address.getHostName(); - int port = address.getPort(); - try { - ChannelFuture channelFuture = bootstrap.connect(host, port).sync(); - Channel channel = channelFuture.channel(); - // 发送数据 - channel.writeAndFlush(request); - //sync()堵塞获取结果 - channel.closeFuture().sync(); - // 阻塞的获得结果,通过给channel设计别名,获取特定名字下的channel中的内容(这个在hanlder中设置) - // AttributeKey是,线程隔离的,不会由线程安全问题。 - // 当前场景下选择堵塞获取结果 - // 其它场景也可以选择添加监听器的方式来异步获取结果 channelFuture.addListener... - AttributeKey key = AttributeKey.valueOf("RPCResponse"); - RpcResponse response = channel.attr(key).get(); - - System.out.println(response); - return response; - } catch (InterruptedException e) { - e.printStackTrace(); - } - return null; - } -} diff --git a/version3/src/main/java/part2/Client/rpcClient/impl/SimpleSocketRpcCilent.java b/version3/src/main/java/part2/Client/rpcClient/impl/SimpleSocketRpcCilent.java deleted file mode 100644 index 8faae62..0000000 --- a/version3/src/main/java/part2/Client/rpcClient/impl/SimpleSocketRpcCilent.java +++ /dev/null @@ -1,41 +0,0 @@ -package part2.Client.rpcClient.impl; - -import part2.Client.rpcClient.RpcClient; -import part2.common.Message.RpcRequest; -import part2.common.Message.RpcResponse; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.net.Socket; - -/** - * @author wxx - * @version 1.0 - * @create 2024/5/2 18:58 - */ -public class SimpleSocketRpcCilent implements RpcClient { - private String host; - private int port; - public SimpleSocketRpcCilent(String host,int port){ - this.host=host; - this.port=port; - } - @Override - public RpcResponse sendRequest(RpcRequest request) { - try { - Socket socket=new Socket(host, port); - ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream()); - ObjectInputStream ois=new ObjectInputStream(socket.getInputStream()); - - oos.writeObject(request); - oos.flush(); - - RpcResponse response=(RpcResponse) ois.readObject(); - return response; - } catch (IOException | ClassNotFoundException e) { - e.printStackTrace(); - return null; - } - } -} diff --git a/version3/src/main/java/part2/Client/serviceCenter/ServiceCenter.java b/version3/src/main/java/part2/Client/serviceCenter/ServiceCenter.java deleted file mode 100644 index ab72194..0000000 --- a/version3/src/main/java/part2/Client/serviceCenter/ServiceCenter.java +++ /dev/null @@ -1,16 +0,0 @@ -package part2.Client.serviceCenter; - -import java.net.InetSocketAddress; - -/** - * @author wxx - * @version 1.0 - * @create 2024/5/3 21:42 - */ -//服务中心接口 -public interface ServiceCenter { - // 查询:根据服务名查找地址 - InetSocketAddress serviceDiscovery(String serviceName); - //判断是否可重试 - boolean checkRetry(String serviceName) ; -} diff --git a/version3/src/main/java/part2/Client/serviceCenter/ZKServiceCenter.java b/version3/src/main/java/part2/Client/serviceCenter/ZKServiceCenter.java deleted file mode 100644 index 4befc04..0000000 --- a/version3/src/main/java/part2/Client/serviceCenter/ZKServiceCenter.java +++ /dev/null @@ -1,93 +0,0 @@ -package part2.Client.serviceCenter; - -import org.apache.curator.RetryPolicy; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.retry.ExponentialBackoffRetry; -import part2.Client.cache.serviceCache; -import part2.Client.serviceCenter.ZkWatcher.watchZK; -import part2.Client.serviceCenter.balance.impl.ConsistencyHashBalance; - -import java.net.InetSocketAddress; -import java.util.List; - -/** - * @author wxx - * @version 1.0 - * @create 2024/5/3 21:41 - */ -public class ZKServiceCenter implements ServiceCenter{ - // curator 提供的zookeeper客户端 - private CuratorFramework client; - //zookeeper根路径节点 - private static final String ROOT_PATH = "MyRPC"; - private static final String RETRY = "CanRetry"; - //serviceCache - private serviceCache cache; - - //负责zookeeper客户端的初始化,并与zookeeper服务端进行连接 - public ZKServiceCenter() throws InterruptedException { - // 指数时间重试 - RetryPolicy policy = new ExponentialBackoffRetry(1000, 3); - // zookeeper的地址固定,不管是服务提供者还是,消费者都要与之建立连接 - // sessionTimeoutMs 与 zoo.cfg中的tickTime 有关系, - // zk还会根据minSessionTimeout与maxSessionTimeout两个参数重新调整最后的超时值。默认分别为tickTime 的2倍和20倍 - // 使用心跳监听状态 - this.client = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181") - .sessionTimeoutMs(40000).retryPolicy(policy).namespace(ROOT_PATH).build(); - this.client.start(); - System.out.println("zookeeper 连接成功"); - //初始化本地缓存 - cache=new serviceCache(); - //加入zookeeper事件监听器 - watchZK watcher=new watchZK(client,cache); - //监听启动 - watcher.watchToUpdate(ROOT_PATH); - } - //根据服务名(接口名)返回地址 - @Override - public InetSocketAddress serviceDiscovery(String serviceName) { - try { - //先从本地缓存中找 - List addressList=cache.getServiceListFromCache(serviceName); - //如果找不到,再去zookeeper中找 - //这种i情况基本不会发生,或者说只会出现在初始化阶段 - if(addressList==null) { - addressList=client.getChildren().forPath("/" + serviceName); - } - // 负载均衡得到地址 - String address = new ConsistencyHashBalance().balance(addressList); - return parseAddress(address); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - // - public boolean checkRetry(String serviceName) { - boolean canRetry =false; - try { - List serviceList = client.getChildren().forPath("/" + RETRY); - for(String s:serviceList){ - if(s.equals(serviceName)){ - System.out.println("服务"+serviceName+"在白名单上,可进行重试"); - canRetry=true; - } - } - }catch (Exception e) { - e.printStackTrace(); - } - return canRetry; - } - // 地址 -> XXX.XXX.XXX.XXX:port 字符串 - private String getServiceAddress(InetSocketAddress serverAddress) { - return serverAddress.getHostName() + - ":" + - serverAddress.getPort(); - } - // 字符串解析为地址 - private InetSocketAddress parseAddress(String address) { - String[] result = address.split(":"); - return new InetSocketAddress(result[0], Integer.parseInt(result[1])); - } -} diff --git a/version3/src/main/java/part2/Client/serviceCenter/ZkWatcher/watchZK.java b/version3/src/main/java/part2/Client/serviceCenter/ZkWatcher/watchZK.java deleted file mode 100644 index 14e9d58..0000000 --- a/version3/src/main/java/part2/Client/serviceCenter/ZkWatcher/watchZK.java +++ /dev/null @@ -1,88 +0,0 @@ -package part2.Client.serviceCenter.ZkWatcher; - -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.recipes.cache.ChildData; -import org.apache.curator.framework.recipes.cache.CuratorCache; -import org.apache.curator.framework.recipes.cache.CuratorCacheListener; -import part2.Client.cache.serviceCache; - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/4 1:00 - */ -public class watchZK { - // curator 提供的zookeeper客户端 - private CuratorFramework client; - //本地缓存 - serviceCache cache; - - - public watchZK(CuratorFramework client,serviceCache cache){ - this.client=client; - this.cache=cache; - } - - /** - * 监听当前节点和子节点的 更新,创建,删除 - * @param path - */ - public void watchToUpdate(String path) throws InterruptedException { - CuratorCache curatorCache = CuratorCache.build(client, "/"); - curatorCache.listenable().addListener(new CuratorCacheListener() { - @Override - public void event(Type type, ChildData childData, ChildData childData1) { - // 第一个参数:事件类型(枚举) - // 第二个参数:节点更新前的状态、数据 - // 第三个参数:节点更新后的状态、数据 - // 创建节点时:节点刚被创建,不存在 更新前节点 ,所以第二个参数为 null - // 删除节点时:节点被删除,不存在 更新后节点 ,所以第三个参数为 null - // 节点创建时没有赋予值 create /curator/app1 只创建节点,在这种情况下,更新前节点的 data 为 null,获取不到更新前节点的数据 - switch (type.name()) { - case "NODE_CREATED": // 监听器第一次执行时节点存在也会触发次事件 - String[] pathList= pasrePath(childData1); - if(pathList.length<=2) break; - else { - String serviceName=pathList[1]; - String address=pathList[2]; - //将新注册的服务加入到本地缓存中 - cache.addServcieToCache(serviceName,address); - } - break; - case "NODE_CHANGED": // 节点更新 - if (childData.getData() != null) { - System.out.println("修改前的数据: " + new String(childData.getData())); - } else { - System.out.println("节点第一次赋值!"); - } - String[] oldPathList=pasrePath(childData); - String[] newPathList=pasrePath(childData1); - cache.replaceServiceAddress(oldPathList[1],oldPathList[2],newPathList[2]); - System.out.println("修改后的数据: " + new String(childData1.getData())); - break; - case "NODE_DELETED": // 节点删除 - String[] pathList_d= pasrePath(childData); - if(pathList_d.length<=2) break; - else { - String serviceName=pathList_d[1]; - String address=pathList_d[2]; - //将新注册的服务加入到本地缓存中 - cache.delete(serviceName,address); - } - break; - default: - break; - } - } - }); - //开启监听 - curatorCache.start(); - } - //解析节点对应地址 - public String[] pasrePath(ChildData childData){ - //获取更新的节点的路径 - String path=new String(childData.getPath()); - //按照格式 ,读取 - return path.split("/"); - } -} \ No newline at end of file diff --git a/version3/src/main/java/part2/Client/serviceCenter/balance/LoadBalance.java b/version3/src/main/java/part2/Client/serviceCenter/balance/LoadBalance.java deleted file mode 100644 index ef28246..0000000 --- a/version3/src/main/java/part2/Client/serviceCenter/balance/LoadBalance.java +++ /dev/null @@ -1,15 +0,0 @@ -package part2.Client.serviceCenter.balance; - -import java.util.List; - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/19 21:00 - * 给服务地址列表,根据不同的负载均衡策略选择一个 - */ -public interface LoadBalance { - String balance(List addressList); - void addNode(String node) ; - void delNode(String node); -} \ No newline at end of file diff --git a/version3/src/main/java/part2/Client/serviceCenter/balance/impl/ConsistencyHashBalance.java b/version3/src/main/java/part2/Client/serviceCenter/balance/impl/ConsistencyHashBalance.java deleted file mode 100644 index 372c79e..0000000 --- a/version3/src/main/java/part2/Client/serviceCenter/balance/impl/ConsistencyHashBalance.java +++ /dev/null @@ -1,119 +0,0 @@ -package part2.Client.serviceCenter.balance.impl; - -import part2.Client.serviceCenter.balance.LoadBalance; - -import java.util.*; - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/19 21:16 - * 一致性哈希算法 负载均衡 - */ -public class ConsistencyHashBalance implements LoadBalance { - // 虚拟节点的个数 - private static final int VIRTUAL_NUM = 5; - - // 虚拟节点分配,key是hash值,value是虚拟节点服务器名称 - private SortedMap shards = new TreeMap(); - - // 真实节点列表 - private List realNodes = new LinkedList(); - - //模拟初始服务器 - private String[] servers =null; - - private void init(List serviceList) { - for (String server :serviceList) { - realNodes.add(server); - System.out.println("真实节点[" + server + "] 被添加"); - for (int i = 0; i < VIRTUAL_NUM; i++) { - String virtualNode = server + "&&VN" + i; - int hash = getHash(virtualNode); - shards.put(hash, virtualNode); - System.out.println("虚拟节点[" + virtualNode + "] hash:" + hash + ",被添加"); - } - } - } - /** - * 获取被分配的节点名 - * - * @param node - * @return - */ - public String getServer(String node,List serviceList) { - init(serviceList); - int hash = getHash(node); - Integer key = null; - SortedMap subMap = shards.tailMap(hash); - if (subMap.isEmpty()) { - key = shards.lastKey(); - } else { - key = subMap.firstKey(); - } - String virtualNode = shards.get(key); - return virtualNode.substring(0, virtualNode.indexOf("&&")); - } - - /** - * 添加节点 - * - * @param node - */ - public void addNode(String node) { - if (!realNodes.contains(node)) { - realNodes.add(node); - System.out.println("真实节点[" + node + "] 上线添加"); - for (int i = 0; i < VIRTUAL_NUM; i++) { - String virtualNode = node + "&&VN" + i; - int hash = getHash(virtualNode); - shards.put(hash, virtualNode); - System.out.println("虚拟节点[" + virtualNode + "] hash:" + hash + ",被添加"); - } - } - } - - /** - * 删除节点 - * - * @param node - */ - public void delNode(String node) { - if (realNodes.contains(node)) { - realNodes.remove(node); - System.out.println("真实节点[" + node + "] 下线移除"); - for (int i = 0; i < VIRTUAL_NUM; i++) { - String virtualNode = node + "&&VN" + i; - int hash = getHash(virtualNode); - shards.remove(hash); - System.out.println("虚拟节点[" + virtualNode + "] hash:" + hash + ",被移除"); - } - } - } - - /** - * FNV1_32_HASH算法 - */ - private static int getHash(String str) { - final int p = 16777619; - int hash = (int) 2166136261L; - for (int i = 0; i < str.length(); i++) - hash = (hash ^ str.charAt(i)) * p; - hash += hash << 13; - hash ^= hash >> 7; - hash += hash << 3; - hash ^= hash >> 17; - hash += hash << 5; - // 如果算出来的值为负数则取其绝对值 - if (hash < 0) - hash = Math.abs(hash); - return hash; - } - - @Override - public String balance(List addressList) { - String random= UUID.randomUUID().toString(); - return getServer(random,addressList); - } - -} diff --git a/version3/src/main/java/part2/Client/serviceCenter/balance/impl/RandomLoadBalance.java b/version3/src/main/java/part2/Client/serviceCenter/balance/impl/RandomLoadBalance.java deleted file mode 100644 index a45602a..0000000 --- a/version3/src/main/java/part2/Client/serviceCenter/balance/impl/RandomLoadBalance.java +++ /dev/null @@ -1,24 +0,0 @@ -package part2.Client.serviceCenter.balance.impl; - -import part2.Client.serviceCenter.balance.LoadBalance; - -import java.util.List; -import java.util.Random; - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/19 21:20 - * 随机 负载均衡 - */ -public class RandomLoadBalance implements LoadBalance { - @Override - public String balance(List addressList) { - Random random=new Random(); - int choose = random.nextInt(addressList.size()); - System.out.println("负载均衡选择了"+choose+"服务器"); - return null; - } - public void addNode(String node){} ; - public void delNode(String node){}; -} diff --git a/version3/src/main/java/part2/Client/serviceCenter/balance/impl/RoundLoadBalance.java b/version3/src/main/java/part2/Client/serviceCenter/balance/impl/RoundLoadBalance.java deleted file mode 100644 index 6748fb4..0000000 --- a/version3/src/main/java/part2/Client/serviceCenter/balance/impl/RoundLoadBalance.java +++ /dev/null @@ -1,24 +0,0 @@ -package part2.Client.serviceCenter.balance.impl; - -import part2.Client.serviceCenter.balance.LoadBalance; - -import java.util.List; - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/19 21:21 - * 轮询 负载均衡 - */ -public class RoundLoadBalance implements LoadBalance { - private int choose=-1; - @Override - public String balance(List addressList) { - choose++; - choose=choose%addressList.size(); - System.out.println("负载均衡选择了"+choose+"服务器"); - return addressList.get(choose); - } - public void addNode(String node) {}; - public void delNode(String node){}; -} diff --git a/version3/src/main/java/part2/Server/TestServer.java b/version3/src/main/java/part2/Server/TestServer.java deleted file mode 100644 index 54941a3..0000000 --- a/version3/src/main/java/part2/Server/TestServer.java +++ /dev/null @@ -1,27 +0,0 @@ -package part2.Server; - - -import part2.Server.provider.ServiceProvider; -import part2.Server.server.RpcServer; -import part2.Server.server.impl.NettyRPCRPCServer; -import part2.common.service.Impl.UserServiceImpl; -import part2.common.service.UserService; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/11 19:39 - */ - -public class TestServer { - public static void main(String[] args) throws InterruptedException { - UserService userService=new UserServiceImpl(); - - ServiceProvider serviceProvider=new ServiceProvider("127.0.0.1",9999); - - serviceProvider.provideServiceInterface(userService,true); - - RpcServer rpcServer=new NettyRPCRPCServer(serviceProvider); - rpcServer.start(9999); - } -} diff --git a/version3/src/main/java/part2/Server/netty/handler/NettyRPCServerHandler.java b/version3/src/main/java/part2/Server/netty/handler/NettyRPCServerHandler.java deleted file mode 100644 index adefac7..0000000 --- a/version3/src/main/java/part2/Server/netty/handler/NettyRPCServerHandler.java +++ /dev/null @@ -1,51 +0,0 @@ -package part2.Server.netty.handler; - -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.SimpleChannelInboundHandler; -import lombok.AllArgsConstructor; -import part2.Server.provider.ServiceProvider; -import part2.common.Message.RpcRequest; -import part2.common.Message.RpcResponse; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/26 16:40 - * 因为是服务器端,我们知道接受到请求格式是RPCRequest - * Object类型也行,强制转型就行 - */ -@AllArgsConstructor -public class NettyRPCServerHandler extends SimpleChannelInboundHandler { - private ServiceProvider serviceProvider; - @Override - protected void channelRead0(ChannelHandlerContext ctx, RpcRequest request) throws Exception { - RpcResponse response = getResponse(request); - ctx.writeAndFlush(response); - ctx.close(); - } - @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { - cause.printStackTrace(); - ctx.close(); - } - private RpcResponse getResponse(RpcRequest rpcRequest){ - //得到服务名 - String interfaceName=rpcRequest.getInterfaceName(); - //得到服务端相应服务实现类 - Object service = serviceProvider.getService(interfaceName); - //反射调用方法 - Method method=null; - try { - method= service.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParamsType()); - Object invoke=method.invoke(service,rpcRequest.getParams()); - return RpcResponse.sussess(invoke); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - e.printStackTrace(); - System.out.println("方法执行错误"); - return RpcResponse.fail(); - } - } -} diff --git a/version3/src/main/java/part2/Server/netty/nettyInitializer/NettyServerInitializer.java b/version3/src/main/java/part2/Server/netty/nettyInitializer/NettyServerInitializer.java deleted file mode 100644 index 4d174a1..0000000 --- a/version3/src/main/java/part2/Server/netty/nettyInitializer/NettyServerInitializer.java +++ /dev/null @@ -1,30 +0,0 @@ -package part2.Server.netty.nettyInitializer; - - -import io.netty.channel.ChannelInitializer; -import io.netty.channel.ChannelPipeline; -import io.netty.channel.socket.SocketChannel; -import lombok.AllArgsConstructor; -import part2.Server.netty.handler.NettyRPCServerHandler; -import part2.Server.provider.ServiceProvider; -import part2.common.serializer.myCode.MyDecoder; -import part2.common.serializer.myCode.MyEncoder; -import part2.common.serializer.mySerializer.JsonSerializer; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/26 16:15 - */ -@AllArgsConstructor -public class NettyServerInitializer extends ChannelInitializer { - private ServiceProvider serviceProvider; - @Override - protected void initChannel(SocketChannel ch) throws Exception { - ChannelPipeline pipeline = ch.pipeline(); - //使用自定义的编/解码器 - pipeline.addLast(new MyEncoder(new JsonSerializer())); - pipeline.addLast(new MyDecoder()); - pipeline.addLast(new NettyRPCServerHandler(serviceProvider)); - } -} diff --git a/version3/src/main/java/part2/Server/provider/ServiceProvider.java b/version3/src/main/java/part2/Server/provider/ServiceProvider.java deleted file mode 100644 index 80e4134..0000000 --- a/version3/src/main/java/part2/Server/provider/ServiceProvider.java +++ /dev/null @@ -1,47 +0,0 @@ -package part2.Server.provider; - -import part2.Server.serviceRegister.ServiceRegister; -import part2.Server.serviceRegister.impl.ZKServiceRegister; - -import java.net.InetSocketAddress; -import java.util.HashMap; -import java.util.Map; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/16 17:35 - */ -public class ServiceProvider { - private Map interfaceProvider; - - private int port; - private String host; - //注册服务类 - private ServiceRegister serviceRegister; - - public ServiceProvider(String host,int port){ - //需要传入服务端自身的网络地址 - this.host=host; - this.port=port; - this.interfaceProvider=new HashMap<>(); - this.serviceRegister=new ZKServiceRegister(); - } - - public void provideServiceInterface(Object service,boolean canRetry){ - String serviceName=service.getClass().getName(); - Class[] interfaceName=service.getClass().getInterfaces(); - - for (Class clazz:interfaceName){ - //本机的映射表 - interfaceProvider.put(clazz.getName(),service); - //在注册中心注册服务 - serviceRegister.register(clazz.getName(),new InetSocketAddress(host,port),canRetry); - } - } - - public Object getService(String interfaceName){ - return interfaceProvider.get(interfaceName); - } - -} diff --git a/version3/src/main/java/part2/Server/server/RpcServer.java b/version3/src/main/java/part2/Server/server/RpcServer.java deleted file mode 100644 index 6abbf2a..0000000 --- a/version3/src/main/java/part2/Server/server/RpcServer.java +++ /dev/null @@ -1,11 +0,0 @@ -package part2.Server.server; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/12 11:26 - */ -public interface RpcServer { - void start(int port); - void stop(); -} diff --git a/version3/src/main/java/part2/Server/server/impl/NettyRPCRPCServer.java b/version3/src/main/java/part2/Server/server/impl/NettyRPCRPCServer.java deleted file mode 100644 index 7a4349a..0000000 --- a/version3/src/main/java/part2/Server/server/impl/NettyRPCRPCServer.java +++ /dev/null @@ -1,48 +0,0 @@ -package part2.Server.server.impl; - -import io.netty.bootstrap.ServerBootstrap; -import io.netty.channel.ChannelFuture; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.nio.NioServerSocketChannel; -import lombok.AllArgsConstructor; -import part2.Server.netty.nettyInitializer.NettyServerInitializer; -import part2.Server.provider.ServiceProvider; -import part2.Server.server.RpcServer; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/26 14:01 - */ -@AllArgsConstructor -public class NettyRPCRPCServer implements RpcServer { - private ServiceProvider serviceProvider; - @Override - public void start(int port) { - // netty 服务线程组boss负责建立连接, work负责具体的请求 - NioEventLoopGroup bossGroup = new NioEventLoopGroup(); - NioEventLoopGroup workGroup = new NioEventLoopGroup(); - System.out.println("netty服务端启动了"); - try { - //启动netty服务器 - ServerBootstrap serverBootstrap = new ServerBootstrap(); - //初始化 - serverBootstrap.group(bossGroup,workGroup).channel(NioServerSocketChannel.class) - .childHandler(new NettyServerInitializer(serviceProvider)); - //同步堵塞 - ChannelFuture channelFuture=serverBootstrap.bind(port).sync(); - //死循环监听 - channelFuture.channel().closeFuture().sync(); - }catch (InterruptedException e){ - e.printStackTrace(); - }finally { - bossGroup.shutdownGracefully(); - workGroup.shutdownGracefully(); - } - } - - @Override - public void stop() { - - } -} diff --git a/version3/src/main/java/part2/Server/server/impl/SimpleRPCRPCServer.java b/version3/src/main/java/part2/Server/server/impl/SimpleRPCRPCServer.java deleted file mode 100644 index 8033bab..0000000 --- a/version3/src/main/java/part2/Server/server/impl/SimpleRPCRPCServer.java +++ /dev/null @@ -1,39 +0,0 @@ -package part2.Server.server.impl; - - -import lombok.AllArgsConstructor; -import part2.Server.provider.ServiceProvider; -import part2.Server.server.RpcServer; -import part2.Server.server.work.WorkThread; - -import java.io.IOException; -import java.net.ServerSocket; -import java.net.Socket; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/12 11:37 - */ -@AllArgsConstructor -public class SimpleRPCRPCServer implements RpcServer { - private ServiceProvider serviceProvide; - @Override - public void start(int port) { - try { - ServerSocket serverSocket=new ServerSocket(port); - System.out.println("服务器启动了"); - while (true) { - Socket socket = serverSocket.accept(); - new Thread(new WorkThread(socket,serviceProvide)).start(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Override - public void stop() { - - } -} diff --git a/version3/src/main/java/part2/Server/server/work/WorkThread.java b/version3/src/main/java/part2/Server/server/work/WorkThread.java deleted file mode 100644 index a3985bf..0000000 --- a/version3/src/main/java/part2/Server/server/work/WorkThread.java +++ /dev/null @@ -1,58 +0,0 @@ -package part2.Server.server.work; - - -import lombok.AllArgsConstructor; -import part2.Server.provider.ServiceProvider; -import part2.common.Message.RpcRequest; -import part2.common.Message.RpcResponse; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.Socket; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/14 17:39 - */ -@AllArgsConstructor -public class WorkThread implements Runnable{ - private Socket socket; - private ServiceProvider serviceProvide; - @Override - public void run() { - try { - ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream()); - ObjectInputStream ois=new ObjectInputStream(socket.getInputStream()); - //读取客户端传过来的request - RpcRequest rpcRequest = (RpcRequest) ois.readObject(); - //反射调用服务方法获取返回值 - RpcResponse rpcResponse=getResponse(rpcRequest); - //向客户端写入response - oos.writeObject(rpcResponse); - oos.flush(); - } catch (IOException | ClassNotFoundException e) { - e.printStackTrace(); - } - } - private RpcResponse getResponse(RpcRequest rpcRequest){ - //得到服务名 - String interfaceName=rpcRequest.getInterfaceName(); - //得到服务端相应服务实现类 - Object service = serviceProvide.getService(interfaceName); - //反射调用方法 - Method method=null; - try { - method= service.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParamsType()); - Object invoke=method.invoke(service,rpcRequest.getParams()); - return RpcResponse.sussess(invoke); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - e.printStackTrace(); - System.out.println("方法执行错误"); - return RpcResponse.fail(); - } - } -} diff --git a/version3/src/main/java/part2/Server/serviceRegister/ServiceRegister.java b/version3/src/main/java/part2/Server/serviceRegister/ServiceRegister.java deleted file mode 100644 index da48e4d..0000000 --- a/version3/src/main/java/part2/Server/serviceRegister/ServiceRegister.java +++ /dev/null @@ -1,15 +0,0 @@ -package part2.Server.serviceRegister; - -import java.net.InetSocketAddress; - -/** - * @author wxx - * @version 1.0 - * @create 2024/5/3 16:58 - */ -// 服务注册接口 -public interface ServiceRegister { - // 注册:保存服务与地址。 - void register(String serviceName, InetSocketAddress serviceAddress,boolean canRetry); - -} diff --git a/version3/src/main/java/part2/Server/serviceRegister/impl/ZKServiceRegister.java b/version3/src/main/java/part2/Server/serviceRegister/impl/ZKServiceRegister.java deleted file mode 100644 index 04e9e7c..0000000 --- a/version3/src/main/java/part2/Server/serviceRegister/impl/ZKServiceRegister.java +++ /dev/null @@ -1,68 +0,0 @@ -package part2.Server.serviceRegister.impl; - -import org.apache.curator.RetryPolicy; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.retry.ExponentialBackoffRetry; -import org.apache.zookeeper.CreateMode; -import part2.Server.serviceRegister.ServiceRegister; - -import java.net.InetSocketAddress; -/** - * @author wxx - * @version 1.0 - * @create 2024/5/3 17:28 - */ -public class ZKServiceRegister implements ServiceRegister { - // curator 提供的zookeeper客户端 - private CuratorFramework client; - //zookeeper根路径节点 - private static final String ROOT_PATH = "MyRPC"; - private static final String RETRY = "CanRetry"; - - //负责zookeeper客户端的初始化,并与zookeeper服务端进行连接 - public ZKServiceRegister(){ - // 指数时间重试 - RetryPolicy policy = new ExponentialBackoffRetry(1000, 3); - // zookeeper的地址固定,不管是服务提供者还是,消费者都要与之建立连接 - // sessionTimeoutMs 与 zoo.cfg中的tickTime 有关系, - // zk还会根据minSessionTimeout与maxSessionTimeout两个参数重新调整最后的超时值。默认分别为tickTime 的2倍和20倍 - // 使用心跳监听状态 - this.client = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181") - .sessionTimeoutMs(40000).retryPolicy(policy).namespace(ROOT_PATH).build(); - this.client.start(); - System.out.println("zookeeper 连接成功"); - } - //注册服务到注册中心 - @Override - public void register(String serviceName, InetSocketAddress serviceAddress,boolean canRetry) { - try { - // serviceName创建成永久节点,服务提供者下线时,不删服务名,只删地址 - if(client.checkExists().forPath("/" + serviceName) == null){ - client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/" + serviceName); - } - // 路径地址,一个/代表一个节点 - String path = "/" + serviceName +"/"+ getServiceAddress(serviceAddress); - // 临时节点,服务器下线就删除节点 - client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path); - //如果这个服务是幂等性,就增加到节点中 - if (canRetry){ - path ="/"+RETRY+"/"+serviceName; - client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path); - } - } catch (Exception e) { - System.out.println("此服务已存在"); - } - } - // 地址 -> XXX.XXX.XXX.XXX:port 字符串 - private String getServiceAddress(InetSocketAddress serverAddress) { - return serverAddress.getHostName() + - ":" + - serverAddress.getPort(); - } - // 字符串解析为地址 - private InetSocketAddress parseAddress(String address) { - String[] result = address.split(":"); - return new InetSocketAddress(result[0], Integer.parseInt(result[1])); - } -} diff --git a/version3/src/main/java/part2/common/Message/MessageType.java b/version3/src/main/java/part2/common/Message/MessageType.java deleted file mode 100644 index 0241fd6..0000000 --- a/version3/src/main/java/part2/common/Message/MessageType.java +++ /dev/null @@ -1,17 +0,0 @@ -package part2.common.Message; - -import lombok.AllArgsConstructor; - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/2 22:29 - */ -@AllArgsConstructor -public enum MessageType { - REQUEST(0),RESPONSE(1); - private int code; - public int getCode(){ - return code; - } -} \ No newline at end of file diff --git a/version3/src/main/java/part2/common/Message/RpcRequest.java b/version3/src/main/java/part2/common/Message/RpcRequest.java deleted file mode 100644 index 9ed8c3a..0000000 --- a/version3/src/main/java/part2/common/Message/RpcRequest.java +++ /dev/null @@ -1,29 +0,0 @@ -package part2.common.Message; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.io.Serializable; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/1 18:30 - * 定义发送的消息格式 - */ -@NoArgsConstructor -@AllArgsConstructor -@Data -@Builder -public class RpcRequest implements Serializable { - //服务类名,客户端只知道接口 - private String interfaceName; - //调用的方法名 - private String methodName; - //参数列表 - private Object[] params; - //参数类型 - private Class[] paramsType; -} diff --git a/version3/src/main/java/part2/common/Message/RpcResponse.java b/version3/src/main/java/part2/common/Message/RpcResponse.java deleted file mode 100644 index 8df2e59..0000000 --- a/version3/src/main/java/part2/common/Message/RpcResponse.java +++ /dev/null @@ -1,35 +0,0 @@ -package part2.common.Message; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.io.Serializable; - -/** - * @author wxx - * @version 1.0 - * @create 2024/2/1 19:18 - */ -@NoArgsConstructor -@AllArgsConstructor -@Data -@Builder -public class RpcResponse implements Serializable { - //状态信息 - private int code; - private String message; - //更新:加入传输数据的类型,以便在自定义序列化器中解析 - private Class dataType; - //具体数据 - private Object data; - - public static RpcResponse sussess(Object data){ - return RpcResponse.builder().code(200).dataType(data.getClass()).data(data).build(); - } - public static RpcResponse fail(){ - return RpcResponse.builder().code(500).message("服务器发生错误").build(); - } -} - diff --git a/version3/src/main/java/part2/common/pojo/User.java b/version3/src/main/java/part2/common/pojo/User.java deleted file mode 100644 index bf999d7..0000000 --- a/version3/src/main/java/part2/common/pojo/User.java +++ /dev/null @@ -1,25 +0,0 @@ -package part2.common.pojo; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.io.Serializable; - -/** - * @author wxx - * @version 1.0 - * @create 2024/1/28 17:50 - */ -@Builder -@Data -@NoArgsConstructor -@AllArgsConstructor -public class User implements Serializable { - // 客户端和服务端共有的 - private Integer id; - private String userName; - private Boolean sex; -} - diff --git a/version3/src/main/java/part2/common/serializer/myCode/MyDecoder.java b/version3/src/main/java/part2/common/serializer/myCode/MyDecoder.java deleted file mode 100644 index 7970141..0000000 --- a/version3/src/main/java/part2/common/serializer/myCode/MyDecoder.java +++ /dev/null @@ -1,41 +0,0 @@ -package part2.common.serializer.myCode; - -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.ByteToMessageDecoder; -import part2.common.Message.MessageType; -import part2.common.serializer.mySerializer.Serializer; - -import java.util.List; - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/2 22:24 - * 按照自定义的消息格式解码数据 - */ -public class MyDecoder extends ByteToMessageDecoder { - @Override - protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List out) throws Exception { - //1.读取消息类型 - short messageType = in.readShort(); - // 现在还只支持request与response请求 - if(messageType != MessageType.REQUEST.getCode() && - messageType != MessageType.RESPONSE.getCode()){ - System.out.println("暂不支持此种数据"); - return; - } - //2.读取序列化的方式&类型 - short serializerType = in.readShort(); - Serializer serializer = Serializer.getSerializerByCode(serializerType); - if(serializer == null) - throw new RuntimeException("不存在对应的序列化器"); - //3.读取序列化数组长度 - int length = in.readInt(); - //4.读取序列化数组 - byte[] bytes=new byte[length]; - in.readBytes(bytes); - Object deserialize= serializer.deserialize(bytes, messageType); - out.add(deserialize); - } -} diff --git a/version3/src/main/java/part2/common/serializer/myCode/MyEncoder.java b/version3/src/main/java/part2/common/serializer/myCode/MyEncoder.java deleted file mode 100644 index c6ef573..0000000 --- a/version3/src/main/java/part2/common/serializer/myCode/MyEncoder.java +++ /dev/null @@ -1,41 +0,0 @@ -package part2.common.serializer.myCode; - -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.MessageToByteEncoder; -import lombok.AllArgsConstructor; -import part2.common.Message.MessageType; -import part2.common.Message.RpcRequest; -import part2.common.Message.RpcResponse; -import part2.common.serializer.mySerializer.Serializer; - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/2 22:24 - * 依次按照自定义的消息格式写入,传入的数据为request或者response - * 需要持有一个serialize器,负责将传入的对象序列化成字节数组 - */ -@AllArgsConstructor -public class MyEncoder extends MessageToByteEncoder { - private Serializer serializer; - @Override - protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception { - System.out.println(msg.getClass()); - //1.写入消息类型 - if(msg instanceof RpcRequest){ - out.writeShort(MessageType.REQUEST.getCode()); - } - else if(msg instanceof RpcResponse){ - out.writeShort(MessageType.RESPONSE.getCode()); - } - //2.写入序列化方式 - out.writeShort(serializer.getType()); - //得到序列化数组 - byte[] serializeBytes = serializer.serialize(msg); - //3.写入长度 - out.writeInt(serializeBytes.length); - //4.写入序列化数组 - out.writeBytes(serializeBytes); - } -} diff --git a/version3/src/main/java/part2/common/serializer/mySerializer/JsonSerializer.java b/version3/src/main/java/part2/common/serializer/mySerializer/JsonSerializer.java deleted file mode 100644 index 63c000b..0000000 --- a/version3/src/main/java/part2/common/serializer/mySerializer/JsonSerializer.java +++ /dev/null @@ -1,65 +0,0 @@ -package part2.common.serializer.mySerializer; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import part2.common.Message.RpcRequest; -import part2.common.Message.RpcResponse; - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/2 22:31 - */ -public class JsonSerializer implements Serializer { - @Override - public byte[] serialize(Object obj) { - byte[] bytes = JSONObject.toJSONBytes(obj); - return bytes; - } - - @Override - public Object deserialize(byte[] bytes, int messageType) { - Object obj = null; - // 传输的消息分为request与response - switch (messageType){ - case 0: - RpcRequest request = JSON.parseObject(bytes, RpcRequest.class); - Object[] objects = new Object[request.getParams().length]; - // 把json字串转化成对应的对象, fastjson可以读出基本数据类型,不用转化 - // 对转换后的request中的params属性逐个进行类型判断 - for(int i = 0; i < objects.length; i++){ - Class paramsType = request.getParamsType()[i]; - //判断每个对象类型是否和paramsTypes中的一致 - if (!paramsType.isAssignableFrom(request.getParams()[i].getClass())){ - //如果不一致,就行进行类型转换 - objects[i] = JSONObject.toJavaObject((JSONObject) request.getParams()[i],request.getParamsType()[i]); - }else{ - //如果一致就直接赋给objects[i] - objects[i] = request.getParams()[i]; - } - } - request.setParams(objects); - obj = request; - break; - case 1: - RpcResponse response = JSON.parseObject(bytes, RpcResponse.class); - Class dataType = response.getDataType(); - //判断转化后的response对象中的data的类型是否正确 - if(! dataType.isAssignableFrom(response.getData().getClass())){ - response.setData(JSONObject.toJavaObject((JSONObject) response.getData(),dataType)); - } - obj = response; - break; - default: - System.out.println("暂时不支持此种消息"); - throw new RuntimeException(); - } - return obj; - } - - //1 代表json序列化方式 - @Override - public int getType() { - return 1; - } -} diff --git a/version3/src/main/java/part2/common/serializer/mySerializer/ObjectSerializer.java b/version3/src/main/java/part2/common/serializer/mySerializer/ObjectSerializer.java deleted file mode 100644 index 5940fb1..0000000 --- a/version3/src/main/java/part2/common/serializer/mySerializer/ObjectSerializer.java +++ /dev/null @@ -1,54 +0,0 @@ -package part2.common.serializer.mySerializer; - -import java.io.*; - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/2 22:36 - */ -public class ObjectSerializer implements Serializer { - //利用Java io 对象 -》字节数组 - @Override - public byte[] serialize(Object obj) { - byte[] bytes=null; - ByteArrayOutputStream bos=new ByteArrayOutputStream(); - try { - //是一个对象输出流,用于将 Java 对象序列化为字节流,并将其连接到bos上 - ObjectOutputStream oos = new ObjectOutputStream(bos); - oos.writeObject(obj); - //刷新 ObjectOutputStream,确保所有缓冲区中的数据都被写入到底层流中。 - oos.flush(); - //将bos其内部缓冲区中的数据转换为字节数组 - bytes = bos.toByteArray(); - oos.close(); - bos.close(); - } catch (IOException e) { - e.printStackTrace(); - } - return bytes; - } - - //字节数组 -》对象 - @Override - public Object deserialize(byte[] bytes, int messageType) { - Object obj = null; - ByteArrayInputStream bis = new ByteArrayInputStream(bytes); - try { - ObjectInputStream ois = new ObjectInputStream(bis); - obj = ois.readObject(); - ois.close(); - bis.close(); - } catch (IOException | ClassNotFoundException e) { - e.printStackTrace(); - } - return obj; - } - - //0 代表Java 原生序列器 - @Override - public int getType() { - return 0; - } -} - diff --git a/version3/src/main/java/part2/common/serializer/mySerializer/Serializer.java b/version3/src/main/java/part2/common/serializer/mySerializer/Serializer.java deleted file mode 100644 index c751d36..0000000 --- a/version3/src/main/java/part2/common/serializer/mySerializer/Serializer.java +++ /dev/null @@ -1,29 +0,0 @@ -package part2.common.serializer.mySerializer; - - -/** - * @author wxx - * @version 1.0 - * @create 2024/6/2 22:31 - */ -public interface Serializer { - // 把对象序列化成字节数组 - byte[] serialize(Object obj); - // 从字节数组反序列化成消息, 使用java自带序列化方式不用messageType也能得到相应的对象(序列化字节数组里包含类信息) - // 其它方式需指定消息格式,再根据message转化成相应的对象 - Object deserialize(byte[] bytes, int messageType); - // 返回使用的序列器,是哪个 - // 0:java自带序列化方式, 1: json序列化方式 - int getType(); - // 根据序号取出序列化器,暂时有两种实现方式,需要其它方式,实现这个接口即可 - static Serializer getSerializerByCode(int code){ - switch (code){ - case 0: - return new ObjectSerializer(); - case 1: - return new JsonSerializer(); - default: - return null; - } - } -} diff --git a/version3/src/main/java/part2/common/service/Impl/UserServiceImpl.java b/version3/src/main/java/part2/common/service/Impl/UserServiceImpl.java deleted file mode 100644 index 37e6262..0000000 --- a/version3/src/main/java/part2/common/service/Impl/UserServiceImpl.java +++ /dev/null @@ -1,32 +0,0 @@ -package part2.common.service.Impl; - - -import part2.common.pojo.User; -import part2.common.service.UserService; - -import java.util.Random; -import java.util.UUID; - -/** - * @author wxx - * @version 1.0 - * @create 2024/1/28 16:28 - */ -public class UserServiceImpl implements UserService { - @Override - public User getUserByUserId(Integer id) { - System.out.println("客户端查询了"+id+"的用户"); - // 模拟从数据库中取用户的行为 - Random random = new Random(); - User user = User.builder().userName(UUID.randomUUID().toString()) - .id(id) - .sex(random.nextBoolean()).build(); - return user; - } - - @Override - public Integer insertUserId(User user) { - System.out.println("插入数据成功"+user.getUserName()); - return user.getId(); - } -} \ No newline at end of file diff --git a/version3/src/main/java/part2/common/service/UserService.java b/version3/src/main/java/part2/common/service/UserService.java deleted file mode 100644 index b6817fe..0000000 --- a/version3/src/main/java/part2/common/service/UserService.java +++ /dev/null @@ -1,16 +0,0 @@ -package part2.common.service; - - -import part2.common.pojo.User; - -/** - * @author wxx - * @version 1.0 - * @create 2024/1/28 16:27 - */ -public interface UserService { - // 客户端通过这个接口调用服务端的实现类 - User getUserByUserId(Integer id); - //新增一个功能 - Integer insertUserId(User user); -} diff --git a/version3/src/main/resources/log4j.properties b/version3/src/main/resources/log4j.properties deleted file mode 100644 index 4e012fe..0000000 --- a/version3/src/main/resources/log4j.properties +++ /dev/null @@ -1,8 +0,0 @@ -log4j.rootLogger=ERROR, stdout -log4j.appender.stdout=org.apache.log4j.ConsoleAppender - -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n -log4j.appender.logfile=org.apache.log4j.FileAppender -log4j.appender.logfile.File=target/spring.log log4j.appender.logfile.layout=org.apache.log4j.PatternLayout -log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n diff --git a/version4/pom.xml b/version4/pom.xml index 254fdb9..e8b0729 100644 --- a/version4/pom.xml +++ b/version4/pom.xml @@ -3,17 +3,28 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.0.0.RELEASE + + org.example version4 1.0-SNAPSHOT + 8 8 8 UTF-8 + + org.springframework.boot + spring-boot-starter-web + org.projectlombok lombok @@ -61,4 +72,22 @@ + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + 8 + 8 + + + + \ No newline at end of file diff --git a/version4/src/main/java/part1/Client/TestClient.java b/version4/src/main/java/part1/Client/TestClient.java index ea18b2a..7e2d407 100644 --- a/version4/src/main/java/part1/Client/TestClient.java +++ b/version4/src/main/java/part1/Client/TestClient.java @@ -1,9 +1,6 @@ package part1.Client; -import part1.Client.proxy.ClientProxy; -import part1.common.pojo.User; -import part1.common.service.UserService; /** @@ -13,29 +10,29 @@ */ public class TestClient { - public static void main(String[] args) throws InterruptedException { - ClientProxy clientProxy=new ClientProxy(); - UserService proxy=clientProxy.getProxy(UserService.class); - for(int i = 0; i < 120; i++) { - Integer i1 = i; - if (i%30==0) { - Thread.sleep(10000); - } - new Thread(()->{ - try{ - User user = proxy.getUserByUserId(i1); - - System.out.println("从服务端得到的user="+user.toString()); - - Integer id = proxy.insertUserId(User.builder().id(i1).userName("User" + i1.toString()).sex(true).build()); - System.out.println("向服务端插入user的id"+id); - } catch (NullPointerException e){ - System.out.println("user为空"); - e.printStackTrace(); - } - }).start(); - } - } +// public static void main(String[] args) throws InterruptedException { +// ClientProxy clientProxy=new ClientProxy(); +// UserService proxy=clientProxy.getProxy(UserService.class); +// for(int i = 0; i < 120; i++) { +// Integer i1 = i; +// if (i%30==0) { +// Thread.sleep(10000); +// } +// new Thread(()->{ +// try{ +// User user = proxy.getUserByUserId(i1); +// +// System.out.println("从服务端得到的user="+user.toString()); +// +// Integer id = proxy.insertUserId(User.builder().id(i1).userName("User" + i1.toString()).sex(true).build()); +// System.out.println("向服务端插入user的id"+id); +// } catch (NullPointerException e){ +// System.out.println("user为空"); +// e.printStackTrace(); +// } +// }).start(); +// } +// } //User user = proxy.getUserByUserId(1); //System.out.println("从服务端得到的user="+user.toString()); // diff --git a/version4/src/main/java/part1/Client/cache/serviceCache.java b/version4/src/main/java/part1/Client/cache/serviceCache.java index 6b29acb..af9ef1b 100644 --- a/version4/src/main/java/part1/Client/cache/serviceCache.java +++ b/version4/src/main/java/part1/Client/cache/serviceCache.java @@ -16,7 +16,7 @@ public class serviceCache { private static Map> cache=new HashMap<>(); //添加服务 - public void addServcieToCache(String serviceName,String address){ + public void addServiceToCache(String serviceName, String address){ if(cache.containsKey(serviceName)){ List addressList = cache.get(serviceName); addressList.add(address); diff --git a/version4/src/main/java/part1/Client/netty/nettyInitializer/NettyClientInitializer.java b/version4/src/main/java/part1/Client/netty/nettyInitializer/NettyClientInitializer.java index e0b520a..31ac08a 100644 --- a/version4/src/main/java/part1/Client/netty/nettyInitializer/NettyClientInitializer.java +++ b/version4/src/main/java/part1/Client/netty/nettyInitializer/NettyClientInitializer.java @@ -8,6 +8,7 @@ import part1.common.serializer.myCode.MyDecoder; import part1.common.serializer.myCode.MyEncoder; import part1.common.serializer.mySerializer.JsonSerializer; +import part1.common.serializer.mySerializer.ObjectSerializer; /** * @author wxx @@ -19,7 +20,7 @@ public class NettyClientInitializer extends ChannelInitializer { protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); //使用自定义的编/解码器 - pipeline.addLast(new MyEncoder(new JsonSerializer())); + pipeline.addLast(new MyEncoder(new ObjectSerializer())); pipeline.addLast(new MyDecoder()); pipeline.addLast(new NettyClientHandler()); } diff --git a/version4/src/main/java/part1/Client/proxy/ClientProxy.java b/version4/src/main/java/part1/Client/proxy/ClientProxy.java index 9f90383..6f09765 100644 --- a/version4/src/main/java/part1/Client/proxy/ClientProxy.java +++ b/version4/src/main/java/part1/Client/proxy/ClientProxy.java @@ -1,6 +1,7 @@ package part1.Client.proxy; +import lombok.extern.slf4j.Slf4j; import part1.Client.circuitBreaker.CircuitBreaker; import part1.Client.circuitBreaker.CircuitBreakerProvider; import part1.Client.retry.guavaRetry; @@ -8,24 +9,30 @@ import part1.Client.rpcClient.impl.NettyRpcClient; import part1.Client.serviceCenter.ServiceCenter; import part1.Client.serviceCenter.ZKServiceCenter; +import part1.Server.integration.References; import part1.common.Message.RpcRequest; import part1.common.Message.RpcResponse; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; +import java.util.HashMap; /** * @author wxx * @version 1.0 * @create 2024/2/6 16:49 */ +@Slf4j public class ClientProxy implements InvocationHandler { //传入参数service接口的class对象,反射封装成一个request private RpcClient rpcClient; private ServiceCenter serviceCenter; private CircuitBreakerProvider circuitBreakerProvider; + private HashMap referencesHashMap = new HashMap<>(); + private References references; + private Class clazz; public ClientProxy() throws InterruptedException { serviceCenter=new ZKServiceCenter(); rpcClient=new NettyRpcClient(serviceCenter); @@ -39,7 +46,9 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl RpcRequest request=RpcRequest.builder() .interfaceName(method.getDeclaringClass().getName()) .methodName(method.getName()) - .params(args).paramsType(method.getParameterTypes()).build(); + .params(args).paramsType(method.getParameterTypes()) + .references(references) + .build(); //获取熔断器 CircuitBreaker circuitBreaker=circuitBreakerProvider.getCircuitBreaker(method.getName()); //判断熔断器是否允许请求经过 @@ -50,7 +59,7 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl //数据传输 RpcResponse response; //后续添加逻辑:为保持幂等性,只对白名单上的服务进行重试 - if (serviceCenter.checkRetry(request.getInterfaceName())){ + if (serviceCenter.checkRetry(request)){ //调用retry框架进行重试操作 response = new guavaRetry().sendServiceWithRetry(request, rpcClient); }else { @@ -66,8 +75,21 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl } return response.getData(); } - public T getProxy(Class clazz){ + + /** + * 获取代理对象 + * @param clazz + * @param rpcReference + * @return + * @param + */ + public T getProxy(Class clazz,References rpcReference){ Object o = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, this); + //记录接口服务与注解信息 + log.info("添加服务:{},注解信息:{}",clazz.getName(),rpcReference.toString()); + referencesHashMap.put(clazz.toString(),rpcReference); + this.references = rpcReference; + this.clazz = clazz; return (T)o; } } diff --git a/version4/src/main/java/part1/Client/rpcClient/impl/NettyRpcClient.java b/version4/src/main/java/part1/Client/rpcClient/impl/NettyRpcClient.java index bca9e15..cd7a0d9 100644 --- a/version4/src/main/java/part1/Client/rpcClient/impl/NettyRpcClient.java +++ b/version4/src/main/java/part1/Client/rpcClient/impl/NettyRpcClient.java @@ -7,6 +7,7 @@ import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.util.AttributeKey; +import lombok.extern.slf4j.Slf4j; import part1.Client.netty.nettyInitializer.NettyClientInitializer; import part1.Client.rpcClient.RpcClient; import part1.common.Message.RpcRequest; @@ -20,6 +21,7 @@ * @version 1.0 * @create 2024/5/2 19:40 */ +@Slf4j public class NettyRpcClient implements RpcClient { private static final Bootstrap bootstrap; @@ -39,8 +41,10 @@ public NettyRpcClient(ServiceCenter serviceCenter) throws InterruptedException { } @Override public RpcResponse sendRequest(RpcRequest request) { + log.info("客户端发生请求" + request); //从注册中心获取host,post - InetSocketAddress address = serviceCenter.serviceDiscovery(request.getInterfaceName()); + InetSocketAddress address = serviceCenter + .serviceDiscovery(request.getInterfaceName() + "." +request.getReferences().version()); String host = address.getHostName(); int port = address.getPort(); try { @@ -57,7 +61,7 @@ public RpcResponse sendRequest(RpcRequest request) { AttributeKey key = AttributeKey.valueOf("RPCResponse"); RpcResponse response = channel.attr(key).get(); - System.out.println(response); + log.info("完成请求——请求返回结果(客户端接受)" + response); return response; } catch (InterruptedException e) { e.printStackTrace(); diff --git a/version4/src/main/java/part1/Client/serviceCenter/ServiceCenter.java b/version4/src/main/java/part1/Client/serviceCenter/ServiceCenter.java index 57a250d..f60a866 100644 --- a/version4/src/main/java/part1/Client/serviceCenter/ServiceCenter.java +++ b/version4/src/main/java/part1/Client/serviceCenter/ServiceCenter.java @@ -1,5 +1,7 @@ package part1.Client.serviceCenter; +import part1.common.Message.RpcRequest; + import java.net.InetSocketAddress; /** @@ -11,6 +13,6 @@ public interface ServiceCenter { // 查询:根据服务名查找地址 InetSocketAddress serviceDiscovery(String serviceName); - //判断是否可重试 - boolean checkRetry(String serviceName) ; + //判断是否可重试,将参数修改为请求,根据请求中注解信息判断是否可重试 + boolean checkRetry(RpcRequest rpcRequest) ; } diff --git a/version4/src/main/java/part1/Client/serviceCenter/ZKServiceCenter.java b/version4/src/main/java/part1/Client/serviceCenter/ZKServiceCenter.java index d549d18..b560122 100644 --- a/version4/src/main/java/part1/Client/serviceCenter/ZKServiceCenter.java +++ b/version4/src/main/java/part1/Client/serviceCenter/ZKServiceCenter.java @@ -7,9 +7,12 @@ import part1.Client.serviceCenter.ZkWatcher.watchZK; import part1.Client.cache.serviceCache; import part1.Client.serviceCenter.balance.impl.ConsistencyHashBalance; +import part1.common.Message.RpcRequest; import java.net.InetSocketAddress; +import java.util.HashMap; import java.util.List; +import java.util.Map; /** * @author wxx @@ -64,21 +67,40 @@ public InetSocketAddress serviceDiscovery(String serviceName) { return null; } // - public boolean checkRetry(String serviceName) { + // TODO 是否可重试的校验修改为 从zoo节点中的注解信息获取 + public boolean checkRetry(RpcRequest rpcRequest) { boolean canRetry =false; try { - List serviceList = client.getChildren().forPath("/" + RETRY); - for(String s:serviceList){ - if(s.equals(serviceName)){ - System.out.println("服务"+serviceName+"在白名单上,可进行重试"); - canRetry=true; - } - } + List serviceList = client.getChildren() + .forPath("/" + rpcRequest.getInterfaceName() + "." + rpcRequest.getReferences().version()); +// for(String s:serviceList){ +// if(s.equals(serviceName)){ +// log.info("服务"+serviceName+"在白名单上,可进行重试"); +// canRetry=true; +// } +// } + String serviceInfo = serviceList.get(0).split("-")[1]; + Map infoMap = convertStringToHashMap(serviceInfo); + return infoMap.get("canRetry").equals("true"); }catch (Exception e) { e.printStackTrace(); } return canRetry; } + public static Map convertStringToHashMap(String str) { + Map map = new HashMap<>(); + if (str != null && !str.isEmpty()) { + str = str.replace("{","").replace("}",""); + String[] pairs = str.split(","); + for (String pair : pairs) { + String[] keyValue = pair.split("="); + if (keyValue.length == 2) { + map.put(keyValue[0].trim(), keyValue[1].trim()); + } + } + } + return map; + } // 地址 -> XXX.XXX.XXX.XXX:port 字符串 private String getServiceAddress(InetSocketAddress serverAddress) { return serverAddress.getHostName() + @@ -87,7 +109,7 @@ private String getServiceAddress(InetSocketAddress serverAddress) { } // 字符串解析为地址 private InetSocketAddress parseAddress(String address) { - String[] result = address.split(":"); + String[] result = address.split("-")[0].split(":"); return new InetSocketAddress(result[0], Integer.parseInt(result[1])); } } diff --git a/version4/src/main/java/part1/Client/serviceCenter/ZkWatcher/watchZK.java b/version4/src/main/java/part1/Client/serviceCenter/ZkWatcher/watchZK.java index e23df29..6aa7fe2 100644 --- a/version4/src/main/java/part1/Client/serviceCenter/ZkWatcher/watchZK.java +++ b/version4/src/main/java/part1/Client/serviceCenter/ZkWatcher/watchZK.java @@ -1,5 +1,6 @@ package part1.Client.serviceCenter.ZkWatcher; +import lombok.extern.slf4j.Slf4j; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.recipes.cache.ChildData; import org.apache.curator.framework.recipes.cache.CuratorCache; @@ -11,6 +12,7 @@ * @version 1.0 * @create 2024/6/4 1:00 */ +@Slf4j public class watchZK { // curator 提供的zookeeper客户端 private CuratorFramework client; @@ -44,9 +46,10 @@ public void event(Type type, ChildData childData, ChildData childData1) { if(pathList.length<=2) break; else { String serviceName=pathList[1]; - String address=pathList[2]; + String address=pathList[2].split("-")[0]; //将新注册的服务加入到本地缓存中 - cache.addServcieToCache(serviceName,address); + cache.addServiceToCache(serviceName,address); + log.info("节点监听-添加,路径集合:{}服务名:{}地址:{}",pathList,serviceName,address); } break; case "NODE_CHANGED": // 节点更新 @@ -66,7 +69,7 @@ public void event(Type type, ChildData childData, ChildData childData1) { else { String serviceName=pathList_d[1]; String address=pathList_d[2]; - //将新注册的服务加入到本地缓存中 + //将删除的服务从本地缓存中删除 cache.delete(serviceName,address); } break; diff --git a/version4/src/main/java/part1/Server/TestServer.java b/version4/src/main/java/part1/Server/TestServer.java index 747e8c6..9f4d025 100644 --- a/version4/src/main/java/part1/Server/TestServer.java +++ b/version4/src/main/java/part1/Server/TestServer.java @@ -4,8 +4,6 @@ import part1.Server.server.impl.NettyRPCRPCServer; import part1.Server.provider.ServiceProvider; import part1.Server.server.RpcServer; -import part1.common.service.Impl.UserServiceImpl; -import part1.common.service.UserService; /** * @author wxx @@ -14,14 +12,14 @@ */ public class TestServer { - public static void main(String[] args) throws InterruptedException { - UserService userService=new UserServiceImpl(); - - ServiceProvider serviceProvider=new ServiceProvider("127.0.0.1",9999); - - serviceProvider.provideServiceInterface(userService,true); - - RpcServer rpcServer=new NettyRPCRPCServer(serviceProvider); - rpcServer.start(9999); - } +// public static void main(String[] args) throws InterruptedException { +// UserService userService=new UserServiceImpl(); +// +// ServiceProvider serviceProvider=new ServiceProvider("127.0.0.1",9999); +// +// serviceProvider.provideServiceInterface(userService,true); +// +// RpcServer rpcServer=new NettyRPCRPCServer(serviceProvider); +// rpcServer.start(9999); +// } } diff --git a/version4/src/main/java/part1/Server/integration/EnableConsumer.java b/version4/src/main/java/part1/Server/integration/EnableConsumer.java new file mode 100644 index 0000000..a7bbfe6 --- /dev/null +++ b/version4/src/main/java/part1/Server/integration/EnableConsumer.java @@ -0,0 +1,21 @@ +package part1.Server.integration; + +import org.springframework.context.annotation.Import; +import part1.Server.integration.configuration.ConsumerPostProcessor; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * @Author: yty + * @Description: 消费者项目启动注解 + * @DateTime: 2024/11/08 16:01 + **/ + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +@Import(ConsumerPostProcessor.class) +public @interface EnableConsumer { +} diff --git a/version4/src/main/java/part1/Server/integration/EnableProvider.java b/version4/src/main/java/part1/Server/integration/EnableProvider.java new file mode 100644 index 0000000..bbcf93c --- /dev/null +++ b/version4/src/main/java/part1/Server/integration/EnableProvider.java @@ -0,0 +1,17 @@ +package part1.Server.integration; + + +import org.springframework.context.annotation.Import; +import part1.Server.integration.configuration.ProviderPostProcessor; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +@Import(ProviderPostProcessor.class) +public @interface EnableProvider { + +} diff --git a/version4/src/main/java/part1/Server/integration/References.java b/version4/src/main/java/part1/Server/integration/References.java new file mode 100644 index 0000000..f779263 --- /dev/null +++ b/version4/src/main/java/part1/Server/integration/References.java @@ -0,0 +1,31 @@ +package part1.Server.integration; + +import org.springframework.stereotype.Component; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target({ElementType.FIELD, ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +@Component +public @interface References { + + /** + * 组号 + * @return + */ + String group() default "1"; + + /** + * 版本号 + * @return + */ + String version() default "1.0"; + + /** + * 负载均衡策略 + */ + String loadBalance() default "RoundLoadBalance"; +} diff --git a/version4/src/main/java/part1/Server/integration/RpcService.java b/version4/src/main/java/part1/Server/integration/RpcService.java new file mode 100644 index 0000000..6c3c2d9 --- /dev/null +++ b/version4/src/main/java/part1/Server/integration/RpcService.java @@ -0,0 +1,50 @@ +package part1.Server.integration; + + +import org.springframework.stereotype.Component; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target({ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +@Component +public @interface RpcService { + + + /** + * 组号 + * @return + */ + String group() default "1"; + + /** + * 版本号 + * @return + */ + String version() default "1.0"; + + /** + * 是否可以重试 + * @return + */ + boolean canRetry() default false; + + /** + * 负载均衡策略 + */ + String loadBalance() default "RoundLoadBalance"; + + /** + * 是否开启服务 + * @return + */ + boolean useAble() default true; + + /** + * 限流阈值-桶令牌算法 + */ + int bucketCAPACITY() default 10; +} diff --git a/version4/src/main/java/part1/Server/integration/configuration/ConsumerPostProcessor.java b/version4/src/main/java/part1/Server/integration/configuration/ConsumerPostProcessor.java new file mode 100644 index 0000000..07bace4 --- /dev/null +++ b/version4/src/main/java/part1/Server/integration/configuration/ConsumerPostProcessor.java @@ -0,0 +1,91 @@ +package part1.Server.integration.configuration; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.context.EnvironmentAware; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import part1.Client.proxy.ClientProxy; +import part1.Server.integration.References; + +import java.lang.reflect.Field; + +/** + * @Author: yty + * @Description: 消费者后置处理器 + * @DateTime: 2024/11/08 16:02 + **/ +@Slf4j +@Configuration +public class ConsumerPostProcessor implements InitializingBean, BeanPostProcessor, EnvironmentAware { + + // 代理对象 +// private static final ClientProxy clientProxy; +// +// static { +// try { +// clientProxy = new ClientProxy(); +// } catch (InterruptedException e) { +// throw new RuntimeException(e); +// } +// } + + + /** + * 读取配置文件后的操作 ——> 启动 RPC 服务 + * @throws Exception + */ + @Override + public void afterPropertiesSet() throws Exception { + } + + /** + * 获取代理对象,发生请求 + * @param bean + * @param beanName + * @return + * @throws BeansException + */ + @Override + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { + // 获取所有字段 + final Field[] fields = bean.getClass().getDeclaredFields(); + // 遍历所有字段找到 RpcReference 注解的字段 + for (Field field : fields) { + if(field.isAnnotationPresent(References.class)){ + final References rpcReference = field.getAnnotation(References.class); + final Class aClass = field.getType(); + field.setAccessible(true); + Object object = null; + try { + ClientProxy clientProxy = new ClientProxy(); + //获取服务代理对象 + log.info("接口类型:{},接口参数:{}",aClass,rpcReference); + object = clientProxy.getProxy(aClass,rpcReference); + } catch (Exception e) { + e.printStackTrace(); + } + try { + // 将消费者的原接口 替换为 RPC的代理对象 + field.set(bean,object); + field.setAccessible(false); + log.info(beanName + " field:" + field.getName() + "注入成功"); + } catch (IllegalAccessException e) { + e.printStackTrace(); + log.info(beanName + " field:" + field.getName() + "注入失败"); + } + } + } + return bean; + } + + /** + * 读取配置文件 + * @param environment + */ + @Override + public void setEnvironment(Environment environment) { + } +} \ No newline at end of file diff --git a/version4/src/main/java/part1/Server/integration/configuration/ProviderPostProcessor.java b/version4/src/main/java/part1/Server/integration/configuration/ProviderPostProcessor.java new file mode 100644 index 0000000..ad07188 --- /dev/null +++ b/version4/src/main/java/part1/Server/integration/configuration/ProviderPostProcessor.java @@ -0,0 +1,78 @@ +package part1.Server.integration.configuration; + + +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.context.EnvironmentAware; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import part1.Server.integration.RpcService; +import part1.Server.provider.ServiceProvider; +import part1.Server.server.RpcServer; +import part1.Server.server.impl.NettyRPCRPCServer; + +/** + * @Author: yty + * @Description: 提供者后置处理器 + * @DateTime: 2024/11/07 23:14 + **/ +@Slf4j +@Configuration +public class ProviderPostProcessor implements InitializingBean,BeanPostProcessor, EnvironmentAware{ + + // TODO 写死本机 + private static final ServiceProvider serviceProvider = new ServiceProvider("127.0.0.1",9999); + + private final RpcServer rpcServer = new NettyRPCRPCServer(serviceProvider); + + /** + * 服务注册 + * @param bean + * @param beanName + * @return + * @throws BeansException + */ + @Override + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { + Class beanClass = bean.getClass(); + // 找到bean上带有 RpcService 注解的类 + RpcService rpcService = beanClass.getAnnotation(RpcService.class); + if (rpcService == null){ + return bean; + } + String group = rpcService.group(); + String version = rpcService.version(); + log.info("获取提供方服务现实bean的实现类类{},组号{},版本号{}",beanClass,group,version); + serviceProvider.provideServiceInterface(bean, rpcService); + return bean; + } + + /** + * 读取配置文件后的操作 ——> 启动 RPC 服务 + * @throws Exception + */ + @Override + public void afterPropertiesSet() throws Exception { + Thread t = new Thread(() -> { + try { + log.info("服务端启动线程"); + rpcServer.start(9999); + } catch (Exception e) { + log.error("启动RPC失败", e); + } + }); + t.setDaemon(true); + t.start(); + + } + + /** + * 读取配置文件 + * @param environment + */ + @Override + public void setEnvironment(Environment environment) { + } +} \ No newline at end of file diff --git a/version4/src/main/java/part1/Server/netty/handler/NettyRPCServerHandler.java b/version4/src/main/java/part1/Server/netty/handler/NettyRPCServerHandler.java index 7b8824f..eb3c01a 100644 --- a/version4/src/main/java/part1/Server/netty/handler/NettyRPCServerHandler.java +++ b/version4/src/main/java/part1/Server/netty/handler/NettyRPCServerHandler.java @@ -3,6 +3,8 @@ import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import part1.Server.integration.References; import part1.Server.provider.ServiceProvider; import part1.Server.ratelimit.RateLimit; import part1.common.Message.RpcRequest; @@ -19,6 +21,7 @@ * Object类型也行,强制转型就行 */ @AllArgsConstructor +@Slf4j public class NettyRPCServerHandler extends SimpleChannelInboundHandler { private ServiceProvider serviceProvider; @Override @@ -33,27 +36,39 @@ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws E ctx.close(); } private RpcResponse getResponse(RpcRequest rpcRequest){ - //得到服务名 - String interfaceName=rpcRequest.getInterfaceName(); - //接口限流降级 + log.info("服务端收到请求" + rpcRequest.toString()); + // 得到客户端接口,注解 + References references = rpcRequest.getReferences(); + String interfaceName = rpcRequest.getInterfaceName() + "." + references.version(); + // TODO 后续根据zookeeper配置中心信息 来决定其它调用配置(比如桶令牌的限流值) + // 接口限流降级 RateLimit rateLimit=serviceProvider.getRateLimitProvider().getRateLimit(interfaceName); if(!rateLimit.getToken()){ //如果获取令牌失败,进行限流降级,快速返回结果 - System.out.println("服务限流!!"); + log.info("服务限流!!"); return RpcResponse.fail(); } - //得到服务端相应服务实现类 Object service = serviceProvider.getService(interfaceName); + log.info("查询的接口名称" + interfaceName); + log.info("服务端相应服务实现类" + service.toString()); //反射调用方法 Method method=null; + boolean isSuccess = false; + Object invoke = null; try { - method= service.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParamsType()); - Object invoke=method.invoke(service,rpcRequest.getParams()); - return RpcResponse.sussess(invoke); + method = service.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParamsType()); + invoke = method.invoke(service,rpcRequest.getParams()); + isSuccess = true; + RpcResponse rpcResponse = new RpcResponse(); + rpcResponse.setCode(200); + rpcResponse.setDataType(invoke.getClass()); + rpcResponse.setData(invoke); + log.info("完成请求——请求返回结果(服务端返回)" + rpcResponse); + return rpcResponse; } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); - System.out.println("方法执行错误"); + log.info("方法执行错误"); return RpcResponse.fail(); } } diff --git a/version4/src/main/java/part1/Server/provider/ServiceProvider.java b/version4/src/main/java/part1/Server/provider/ServiceProvider.java index 30064d1..fb046af 100644 --- a/version4/src/main/java/part1/Server/provider/ServiceProvider.java +++ b/version4/src/main/java/part1/Server/provider/ServiceProvider.java @@ -1,5 +1,7 @@ package part1.Server.provider; +import lombok.extern.slf4j.Slf4j; +import part1.Server.integration.RpcService; import part1.Server.ratelimit.provider.RateLimitProvider; import part1.Server.serviceRegister.impl.ZKServiceRegister; import part1.Server.serviceRegister.ServiceRegister; @@ -13,6 +15,7 @@ * @version 1.0 * @create 2024/2/16 17:35 */ +@Slf4j public class ServiceProvider { private Map interfaceProvider; @@ -31,15 +34,18 @@ public ServiceProvider(String host,int port){ this.rateLimitProvider=new RateLimitProvider(); } - public void provideServiceInterface(Object service,boolean canRetry){ + public void provideServiceInterface(Object service, RpcService rpcService){ String serviceName=service.getClass().getName(); Class[] interfaceName=service.getClass().getInterfaces(); - + String version = rpcService.version(); + boolean canRetry = rpcService.canRetry(); for (Class clazz:interfaceName){ - //本机的映射表 - interfaceProvider.put(clazz.getName(),service); - //在注册中心注册服务 - serviceRegister.register(clazz.getName(),new InetSocketAddress(host,port),canRetry); + String serviceAndVersion = clazz.getName() + "." + version; + //本机的映射表(接口名+版本号 : 实现类) + interfaceProvider.put(serviceAndVersion,service); + log.info("本机映射表存储{}:{}", serviceAndVersion,service); + //在注册中心注册服务 (注册中心是用于注册 服务——服务地址,是用来给客户端返回服务地址的) + serviceRegister.register(serviceAndVersion,new InetSocketAddress(host,port),rpcService); } } diff --git a/version4/src/main/java/part1/Server/server/impl/NettyRPCRPCServer.java b/version4/src/main/java/part1/Server/server/impl/NettyRPCRPCServer.java index 514b857..44c616c 100644 --- a/version4/src/main/java/part1/Server/server/impl/NettyRPCRPCServer.java +++ b/version4/src/main/java/part1/Server/server/impl/NettyRPCRPCServer.java @@ -5,6 +5,7 @@ import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; import part1.Server.netty.nettyInitializer.NettyServerInitializer; import part1.Server.provider.ServiceProvider; import part1.Server.server.RpcServer; @@ -15,6 +16,7 @@ * @create 2024/2/26 14:01 */ @AllArgsConstructor +@Slf4j public class NettyRPCRPCServer implements RpcServer { private ServiceProvider serviceProvider; @Override diff --git a/version4/src/main/java/part1/Server/serviceRegister/ServiceRegister.java b/version4/src/main/java/part1/Server/serviceRegister/ServiceRegister.java index 0f94e4d..212feaf 100644 --- a/version4/src/main/java/part1/Server/serviceRegister/ServiceRegister.java +++ b/version4/src/main/java/part1/Server/serviceRegister/ServiceRegister.java @@ -1,5 +1,7 @@ package part1.Server.serviceRegister; +import part1.Server.integration.RpcService; + import java.net.InetSocketAddress; /** @@ -9,7 +11,8 @@ */ // 服务注册接口 public interface ServiceRegister { - // 注册:保存服务与地址。 - void register(String serviceName, InetSocketAddress serviceAddress,boolean canRetry); + // 注册:保存服务与地址。 将服务信息都保存在注解中 + //void register(String serviceName, InetSocketAddress serviceAddress,boolean canRetry); + void register(String serviceName, InetSocketAddress serviceAddress, RpcService rpcService); } diff --git a/version4/src/main/java/part1/Server/serviceRegister/impl/ZKServiceRegister.java b/version4/src/main/java/part1/Server/serviceRegister/impl/ZKServiceRegister.java index 6d4bb6f..60f9c54 100644 --- a/version4/src/main/java/part1/Server/serviceRegister/impl/ZKServiceRegister.java +++ b/version4/src/main/java/part1/Server/serviceRegister/impl/ZKServiceRegister.java @@ -1,10 +1,13 @@ package part1.Server.serviceRegister.impl; +import lombok.extern.slf4j.Slf4j; import org.apache.curator.RetryPolicy; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.zookeeper.CreateMode; +import org.springframework.core.annotation.AnnotationUtils; +import part1.Server.integration.RpcService; import part1.Server.serviceRegister.ServiceRegister; import java.net.InetSocketAddress; @@ -13,6 +16,7 @@ * @version 1.0 * @create 2024/5/3 17:28 */ +@Slf4j public class ZKServiceRegister implements ServiceRegister { // curator 提供的zookeeper客户端 private CuratorFramework client; @@ -35,23 +39,23 @@ public ZKServiceRegister(){ } //注册服务到注册中心 @Override - public void register(String serviceName, InetSocketAddress serviceAddress,boolean canRetry) { + public void register(String serviceName, InetSocketAddress serviceAddress, RpcService rpcService) { try { // serviceName创建成永久节点,服务提供者下线时,不删服务名,只删地址 if(client.checkExists().forPath("/" + serviceName) == null){ client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/" + serviceName); } // 路径地址,一个/代表一个节点 - String path = "/" + serviceName +"/"+ getServiceAddress(serviceAddress); + String path = "/" + serviceName +"/"+ getServiceAddress(serviceAddress) + "-"+ AnnotationUtils.getAnnotationAttributes(rpcService);; // 临时节点,服务器下线就删除节点 client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path); - //如果这个服务是幂等性,就增加到节点中 - if (canRetry){ + // 取消RETRY节点,将幂等性等信息存到服务节点中 + if (rpcService.canRetry()){ path ="/"+RETRY+"/"+serviceName; client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path); } } catch (Exception e) { - System.out.println("此服务已存在"); + log.info(serviceName+"此服务已存在"); } } // 地址 -> XXX.XXX.XXX.XXX:port 字符串 diff --git a/version4/src/main/java/part1/common/Message/RpcRequest.java b/version4/src/main/java/part1/common/Message/RpcRequest.java index 2642f38..0fe22d4 100644 --- a/version4/src/main/java/part1/common/Message/RpcRequest.java +++ b/version4/src/main/java/part1/common/Message/RpcRequest.java @@ -4,6 +4,7 @@ import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; +import part1.Server.integration.References; import java.io.Serializable; @@ -20,6 +21,8 @@ public class RpcRequest implements Serializable { //服务类名,客户端只知道接口 private String interfaceName; + //客户端接口注解 + private References references; //调用的方法名 private String methodName; //参数列表 diff --git a/version4/src/main/java/part1/common/pojo/User.java b/version4/src/main/java/part1/common/pojo/User.java deleted file mode 100644 index d7cef8c..0000000 --- a/version4/src/main/java/part1/common/pojo/User.java +++ /dev/null @@ -1,25 +0,0 @@ -package part1.common.pojo; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.io.Serializable; - -/** - * @author wxx - * @version 1.0 - * @create 2024/1/28 17:50 - */ -@Builder -@Data -@NoArgsConstructor -@AllArgsConstructor -public class User implements Serializable { - // 客户端和服务端共有的 - private Integer id; - private String userName; - private Boolean sex; -} - diff --git a/version4/src/main/java/part1/common/service/Impl/UserServiceImpl.java b/version4/src/main/java/part1/common/service/Impl/UserServiceImpl.java deleted file mode 100644 index 373243b..0000000 --- a/version4/src/main/java/part1/common/service/Impl/UserServiceImpl.java +++ /dev/null @@ -1,32 +0,0 @@ -package part1.common.service.Impl; - - -import part1.common.pojo.User; -import part1.common.service.UserService; - -import java.util.Random; -import java.util.UUID; - -/** - * @author wxx - * @version 1.0 - * @create 2024/1/28 16:28 - */ -public class UserServiceImpl implements UserService { - @Override - public User getUserByUserId(Integer id) { - System.out.println("客户端查询了"+id+"的用户"); - // 模拟从数据库中取用户的行为 - Random random = new Random(); - User user = User.builder().userName(UUID.randomUUID().toString()) - .id(id) - .sex(random.nextBoolean()).build(); - return user; - } - - @Override - public Integer insertUserId(User user) { - System.out.println("插入数据成功"+user.getUserName()); - return user.getId(); - } -} \ No newline at end of file diff --git a/version4/src/main/java/part1/common/service/UserService.java b/version4/src/main/java/part1/common/service/UserService.java deleted file mode 100644 index 0e539bd..0000000 --- a/version4/src/main/java/part1/common/service/UserService.java +++ /dev/null @@ -1,16 +0,0 @@ -package part1.common.service; - - -import part1.common.pojo.User; - -/** - * @author wxx - * @version 1.0 - * @create 2024/1/28 16:27 - */ -public interface UserService { - // 客户端通过这个接口调用服务端的实现类 - User getUserByUserId(Integer id); - //新增一个功能 - Integer insertUserId(User user); -} diff --git a/version1/src/main/resources/log4j.properties b/version4/target/classes/log4j.properties similarity index 100% rename from version1/src/main/resources/log4j.properties rename to version4/target/classes/log4j.properties diff --git a/version4/target/classes/part1/Client/TestClient.class b/version4/target/classes/part1/Client/TestClient.class new file mode 100644 index 0000000..547fcc0 Binary files /dev/null and b/version4/target/classes/part1/Client/TestClient.class differ diff --git a/version4/target/classes/part1/Client/cache/serviceCache.class b/version4/target/classes/part1/Client/cache/serviceCache.class new file mode 100644 index 0000000..97c67f6 Binary files /dev/null and b/version4/target/classes/part1/Client/cache/serviceCache.class differ diff --git a/version4/target/classes/part1/Client/circuitBreaker/CircuitBreaker$1.class b/version4/target/classes/part1/Client/circuitBreaker/CircuitBreaker$1.class new file mode 100644 index 0000000..e8173dd Binary files /dev/null and b/version4/target/classes/part1/Client/circuitBreaker/CircuitBreaker$1.class differ diff --git a/version4/target/classes/part1/Client/circuitBreaker/CircuitBreaker.class b/version4/target/classes/part1/Client/circuitBreaker/CircuitBreaker.class new file mode 100644 index 0000000..0efffec Binary files /dev/null and b/version4/target/classes/part1/Client/circuitBreaker/CircuitBreaker.class differ diff --git a/version4/target/classes/part1/Client/circuitBreaker/CircuitBreakerProvider.class b/version4/target/classes/part1/Client/circuitBreaker/CircuitBreakerProvider.class new file mode 100644 index 0000000..fe223a2 Binary files /dev/null and b/version4/target/classes/part1/Client/circuitBreaker/CircuitBreakerProvider.class differ diff --git a/version4/target/classes/part1/Client/circuitBreaker/CircuitBreakerState.class b/version4/target/classes/part1/Client/circuitBreaker/CircuitBreakerState.class new file mode 100644 index 0000000..615b528 Binary files /dev/null and b/version4/target/classes/part1/Client/circuitBreaker/CircuitBreakerState.class differ diff --git a/version4/target/classes/part1/Client/netty/handler/NettyClientHandler.class b/version4/target/classes/part1/Client/netty/handler/NettyClientHandler.class new file mode 100644 index 0000000..cbfc833 Binary files /dev/null and b/version4/target/classes/part1/Client/netty/handler/NettyClientHandler.class differ diff --git a/version4/target/classes/part1/Client/netty/nettyInitializer/NettyClientInitializer.class b/version4/target/classes/part1/Client/netty/nettyInitializer/NettyClientInitializer.class new file mode 100644 index 0000000..180dc86 Binary files /dev/null and b/version4/target/classes/part1/Client/netty/nettyInitializer/NettyClientInitializer.class differ diff --git a/version4/target/classes/part1/Client/proxy/ClientProxy.class b/version4/target/classes/part1/Client/proxy/ClientProxy.class new file mode 100644 index 0000000..73320a5 Binary files /dev/null and b/version4/target/classes/part1/Client/proxy/ClientProxy.class differ diff --git a/version4/target/classes/part1/Client/retry/guavaRetry$1.class b/version4/target/classes/part1/Client/retry/guavaRetry$1.class new file mode 100644 index 0000000..74be38d Binary files /dev/null and b/version4/target/classes/part1/Client/retry/guavaRetry$1.class differ diff --git a/version4/target/classes/part1/Client/retry/guavaRetry.class b/version4/target/classes/part1/Client/retry/guavaRetry.class new file mode 100644 index 0000000..d52d563 Binary files /dev/null and b/version4/target/classes/part1/Client/retry/guavaRetry.class differ diff --git a/version4/target/classes/part1/Client/rpcClient/RpcClient.class b/version4/target/classes/part1/Client/rpcClient/RpcClient.class new file mode 100644 index 0000000..8ab712d Binary files /dev/null and b/version4/target/classes/part1/Client/rpcClient/RpcClient.class differ diff --git a/version4/target/classes/part1/Client/rpcClient/impl/NettyRpcClient.class b/version4/target/classes/part1/Client/rpcClient/impl/NettyRpcClient.class new file mode 100644 index 0000000..5c75dbb Binary files /dev/null and b/version4/target/classes/part1/Client/rpcClient/impl/NettyRpcClient.class differ diff --git a/version4/target/classes/part1/Client/rpcClient/impl/SimpleSocketRpcCilent.class b/version4/target/classes/part1/Client/rpcClient/impl/SimpleSocketRpcCilent.class new file mode 100644 index 0000000..b69db85 Binary files /dev/null and b/version4/target/classes/part1/Client/rpcClient/impl/SimpleSocketRpcCilent.class differ diff --git a/version4/target/classes/part1/Client/serviceCenter/ServiceCenter.class b/version4/target/classes/part1/Client/serviceCenter/ServiceCenter.class new file mode 100644 index 0000000..e7b41a3 Binary files /dev/null and b/version4/target/classes/part1/Client/serviceCenter/ServiceCenter.class differ diff --git a/version4/target/classes/part1/Client/serviceCenter/ZKServiceCenter.class b/version4/target/classes/part1/Client/serviceCenter/ZKServiceCenter.class new file mode 100644 index 0000000..3aeb2eb Binary files /dev/null and b/version4/target/classes/part1/Client/serviceCenter/ZKServiceCenter.class differ diff --git a/version4/target/classes/part1/Client/serviceCenter/ZkWatcher/watchZK$1.class b/version4/target/classes/part1/Client/serviceCenter/ZkWatcher/watchZK$1.class new file mode 100644 index 0000000..2f0fe54 Binary files /dev/null and b/version4/target/classes/part1/Client/serviceCenter/ZkWatcher/watchZK$1.class differ diff --git a/version4/target/classes/part1/Client/serviceCenter/ZkWatcher/watchZK.class b/version4/target/classes/part1/Client/serviceCenter/ZkWatcher/watchZK.class new file mode 100644 index 0000000..7032b83 Binary files /dev/null and b/version4/target/classes/part1/Client/serviceCenter/ZkWatcher/watchZK.class differ diff --git a/version4/target/classes/part1/Client/serviceCenter/balance/LoadBalance.class b/version4/target/classes/part1/Client/serviceCenter/balance/LoadBalance.class new file mode 100644 index 0000000..f4aeffc Binary files /dev/null and b/version4/target/classes/part1/Client/serviceCenter/balance/LoadBalance.class differ diff --git a/version4/target/classes/part1/Client/serviceCenter/balance/impl/ConsistencyHashBalance.class b/version4/target/classes/part1/Client/serviceCenter/balance/impl/ConsistencyHashBalance.class new file mode 100644 index 0000000..ccad7f5 Binary files /dev/null and b/version4/target/classes/part1/Client/serviceCenter/balance/impl/ConsistencyHashBalance.class differ diff --git a/version4/target/classes/part1/Client/serviceCenter/balance/impl/RandomLoadBalance.class b/version4/target/classes/part1/Client/serviceCenter/balance/impl/RandomLoadBalance.class new file mode 100644 index 0000000..f28f54b Binary files /dev/null and b/version4/target/classes/part1/Client/serviceCenter/balance/impl/RandomLoadBalance.class differ diff --git a/version4/target/classes/part1/Client/serviceCenter/balance/impl/RoundLoadBalance.class b/version4/target/classes/part1/Client/serviceCenter/balance/impl/RoundLoadBalance.class new file mode 100644 index 0000000..8d045a4 Binary files /dev/null and b/version4/target/classes/part1/Client/serviceCenter/balance/impl/RoundLoadBalance.class differ diff --git a/version4/target/classes/part1/Server/TestServer.class b/version4/target/classes/part1/Server/TestServer.class new file mode 100644 index 0000000..026c7e9 Binary files /dev/null and b/version4/target/classes/part1/Server/TestServer.class differ diff --git a/version4/target/classes/part1/Server/integration/EnableConsumer.class b/version4/target/classes/part1/Server/integration/EnableConsumer.class new file mode 100644 index 0000000..49bd6f6 Binary files /dev/null and b/version4/target/classes/part1/Server/integration/EnableConsumer.class differ diff --git a/version4/target/classes/part1/Server/integration/EnableProvider.class b/version4/target/classes/part1/Server/integration/EnableProvider.class new file mode 100644 index 0000000..e8ef17f Binary files /dev/null and b/version4/target/classes/part1/Server/integration/EnableProvider.class differ diff --git a/version4/target/classes/part1/Server/integration/References.class b/version4/target/classes/part1/Server/integration/References.class new file mode 100644 index 0000000..33a1bf9 Binary files /dev/null and b/version4/target/classes/part1/Server/integration/References.class differ diff --git a/version4/target/classes/part1/Server/integration/RpcService.class b/version4/target/classes/part1/Server/integration/RpcService.class new file mode 100644 index 0000000..d888bde Binary files /dev/null and b/version4/target/classes/part1/Server/integration/RpcService.class differ diff --git a/version4/target/classes/part1/Server/integration/configuration/ConsumerPostProcessor.class b/version4/target/classes/part1/Server/integration/configuration/ConsumerPostProcessor.class new file mode 100644 index 0000000..79c3f12 Binary files /dev/null and b/version4/target/classes/part1/Server/integration/configuration/ConsumerPostProcessor.class differ diff --git a/version4/target/classes/part1/Server/integration/configuration/ProviderPostProcessor.class b/version4/target/classes/part1/Server/integration/configuration/ProviderPostProcessor.class new file mode 100644 index 0000000..7d3ec55 Binary files /dev/null and b/version4/target/classes/part1/Server/integration/configuration/ProviderPostProcessor.class differ diff --git a/version4/target/classes/part1/Server/netty/handler/NettyRPCServerHandler.class b/version4/target/classes/part1/Server/netty/handler/NettyRPCServerHandler.class new file mode 100644 index 0000000..8dc2646 Binary files /dev/null and b/version4/target/classes/part1/Server/netty/handler/NettyRPCServerHandler.class differ diff --git a/version4/target/classes/part1/Server/netty/nettyInitializer/NettyServerInitializer.class b/version4/target/classes/part1/Server/netty/nettyInitializer/NettyServerInitializer.class new file mode 100644 index 0000000..775b163 Binary files /dev/null and b/version4/target/classes/part1/Server/netty/nettyInitializer/NettyServerInitializer.class differ diff --git a/version4/target/classes/part1/Server/provider/ServiceProvider.class b/version4/target/classes/part1/Server/provider/ServiceProvider.class new file mode 100644 index 0000000..94a1aa8 Binary files /dev/null and b/version4/target/classes/part1/Server/provider/ServiceProvider.class differ diff --git a/version4/target/classes/part1/Server/ratelimit/RateLimit.class b/version4/target/classes/part1/Server/ratelimit/RateLimit.class new file mode 100644 index 0000000..d13f5b7 Binary files /dev/null and b/version4/target/classes/part1/Server/ratelimit/RateLimit.class differ diff --git a/version4/target/classes/part1/Server/ratelimit/impl/TokenBucketRateLimitImpl.class b/version4/target/classes/part1/Server/ratelimit/impl/TokenBucketRateLimitImpl.class new file mode 100644 index 0000000..93caa1e Binary files /dev/null and b/version4/target/classes/part1/Server/ratelimit/impl/TokenBucketRateLimitImpl.class differ diff --git a/version4/target/classes/part1/Server/ratelimit/provider/RateLimitProvider.class b/version4/target/classes/part1/Server/ratelimit/provider/RateLimitProvider.class new file mode 100644 index 0000000..492c2b8 Binary files /dev/null and b/version4/target/classes/part1/Server/ratelimit/provider/RateLimitProvider.class differ diff --git a/version4/target/classes/part1/Server/server/RpcServer.class b/version4/target/classes/part1/Server/server/RpcServer.class new file mode 100644 index 0000000..260e315 Binary files /dev/null and b/version4/target/classes/part1/Server/server/RpcServer.class differ diff --git a/version4/target/classes/part1/Server/server/impl/NettyRPCRPCServer.class b/version4/target/classes/part1/Server/server/impl/NettyRPCRPCServer.class new file mode 100644 index 0000000..1474c29 Binary files /dev/null and b/version4/target/classes/part1/Server/server/impl/NettyRPCRPCServer.class differ diff --git a/version4/target/classes/part1/Server/server/impl/SimpleRPCRPCServer.class b/version4/target/classes/part1/Server/server/impl/SimpleRPCRPCServer.class new file mode 100644 index 0000000..032682c Binary files /dev/null and b/version4/target/classes/part1/Server/server/impl/SimpleRPCRPCServer.class differ diff --git a/version1/target/classes/part1/Server/server/work/WorkThread.class b/version4/target/classes/part1/Server/server/work/WorkThread.class similarity index 67% rename from version1/target/classes/part1/Server/server/work/WorkThread.class rename to version4/target/classes/part1/Server/server/work/WorkThread.class index e26c777..73f08f5 100644 Binary files a/version1/target/classes/part1/Server/server/work/WorkThread.class and b/version4/target/classes/part1/Server/server/work/WorkThread.class differ diff --git a/version4/target/classes/part1/Server/serviceRegister/ServiceRegister.class b/version4/target/classes/part1/Server/serviceRegister/ServiceRegister.class new file mode 100644 index 0000000..8df4732 Binary files /dev/null and b/version4/target/classes/part1/Server/serviceRegister/ServiceRegister.class differ diff --git a/version4/target/classes/part1/Server/serviceRegister/impl/ZKServiceRegister.class b/version4/target/classes/part1/Server/serviceRegister/impl/ZKServiceRegister.class new file mode 100644 index 0000000..e04a26a Binary files /dev/null and b/version4/target/classes/part1/Server/serviceRegister/impl/ZKServiceRegister.class differ diff --git a/version4/target/classes/part1/common/Message/MessageType.class b/version4/target/classes/part1/common/Message/MessageType.class new file mode 100644 index 0000000..ee9f611 Binary files /dev/null and b/version4/target/classes/part1/common/Message/MessageType.class differ diff --git a/version4/target/classes/part1/common/Message/RpcRequest$RpcRequestBuilder.class b/version4/target/classes/part1/common/Message/RpcRequest$RpcRequestBuilder.class new file mode 100644 index 0000000..712f1e2 Binary files /dev/null and b/version4/target/classes/part1/common/Message/RpcRequest$RpcRequestBuilder.class differ diff --git a/version4/target/classes/part1/common/Message/RpcRequest.class b/version4/target/classes/part1/common/Message/RpcRequest.class new file mode 100644 index 0000000..69e334d Binary files /dev/null and b/version4/target/classes/part1/common/Message/RpcRequest.class differ diff --git a/version4/target/classes/part1/common/Message/RpcResponse$RpcResponseBuilder.class b/version4/target/classes/part1/common/Message/RpcResponse$RpcResponseBuilder.class new file mode 100644 index 0000000..f83201b Binary files /dev/null and b/version4/target/classes/part1/common/Message/RpcResponse$RpcResponseBuilder.class differ diff --git a/version4/target/classes/part1/common/Message/RpcResponse.class b/version4/target/classes/part1/common/Message/RpcResponse.class new file mode 100644 index 0000000..214a03a Binary files /dev/null and b/version4/target/classes/part1/common/Message/RpcResponse.class differ diff --git a/version4/target/classes/part1/common/serializer/myCode/MyDecoder.class b/version4/target/classes/part1/common/serializer/myCode/MyDecoder.class new file mode 100644 index 0000000..593de60 Binary files /dev/null and b/version4/target/classes/part1/common/serializer/myCode/MyDecoder.class differ diff --git a/version4/target/classes/part1/common/serializer/myCode/MyEncoder.class b/version4/target/classes/part1/common/serializer/myCode/MyEncoder.class new file mode 100644 index 0000000..7714208 Binary files /dev/null and b/version4/target/classes/part1/common/serializer/myCode/MyEncoder.class differ diff --git a/version4/target/classes/part1/common/serializer/mySerializer/JsonSerializer.class b/version4/target/classes/part1/common/serializer/mySerializer/JsonSerializer.class new file mode 100644 index 0000000..3bdb648 Binary files /dev/null and b/version4/target/classes/part1/common/serializer/mySerializer/JsonSerializer.class differ diff --git a/version4/target/classes/part1/common/serializer/mySerializer/ObjectSerializer.class b/version4/target/classes/part1/common/serializer/mySerializer/ObjectSerializer.class new file mode 100644 index 0000000..8530589 Binary files /dev/null and b/version4/target/classes/part1/common/serializer/mySerializer/ObjectSerializer.class differ diff --git a/version4/target/classes/part1/common/serializer/mySerializer/Serializer.class b/version4/target/classes/part1/common/serializer/mySerializer/Serializer.class new file mode 100644 index 0000000..3c56055 Binary files /dev/null and b/version4/target/classes/part1/common/serializer/mySerializer/Serializer.class differ diff --git a/version5/.idea/compiler.xml b/version5/.idea/compiler.xml deleted file mode 100644 index c8f73e3..0000000 --- a/version5/.idea/compiler.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/version5/.idea/encodings.xml b/version5/.idea/encodings.xml deleted file mode 100644 index 1da27bf..0000000 --- a/version5/.idea/encodings.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/version5/.idea/inspectionProfiles/Project_Default.xml b/version5/.idea/inspectionProfiles/Project_Default.xml deleted file mode 100644 index c8e8ddc..0000000 --- a/version5/.idea/inspectionProfiles/Project_Default.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - \ No newline at end of file diff --git a/version5/.idea/jarRepositories.xml b/version5/.idea/jarRepositories.xml deleted file mode 100644 index 5a2f139..0000000 --- a/version5/.idea/jarRepositories.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/version5/.idea/misc.xml b/version5/.idea/misc.xml deleted file mode 100644 index 4914f21..0000000 --- a/version5/.idea/misc.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/version5/.idea/uiDesigner.xml b/version5/.idea/uiDesigner.xml deleted file mode 100644 index 2b63946..0000000 --- a/version5/.idea/uiDesigner.xml +++ /dev/null @@ -1,124 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/version5/.idea/vcs.xml b/version5/.idea/vcs.xml deleted file mode 100644 index d843f34..0000000 --- a/version5/.idea/vcs.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/version5/krpc-api/pom.xml b/version5/krpc-api/pom.xml deleted file mode 100644 index c0f741b..0000000 --- a/version5/krpc-api/pom.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - 4.0.0 - - com.kama - version5 - 1.0-SNAPSHOT - - - krpc-api - - - 17 - 17 - UTF-8 - - - \ No newline at end of file diff --git a/version5/krpc-api/src/main/java/com/kama/pojo/User.java b/version5/krpc-api/src/main/java/com/kama/pojo/User.java deleted file mode 100644 index 3713995..0000000 --- a/version5/krpc-api/src/main/java/com/kama/pojo/User.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.kama.pojo; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.io.Serializable; - -/** - * @ClassName User - * @Description User对象 - * @Author Tong - * @LastChangeDate 2024-12-05 0:53 - * @Version v5.0 - */ -@Builder -@Data -@NoArgsConstructor -@AllArgsConstructor -public class User implements Serializable { - // 客户端和服务端共有的 - private Integer id; - private String userName; - private Boolean gender; -} diff --git a/version5/krpc-api/src/main/java/com/kama/service/UserService.java b/version5/krpc-api/src/main/java/com/kama/service/UserService.java deleted file mode 100644 index 388978b..0000000 --- a/version5/krpc-api/src/main/java/com/kama/service/UserService.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.kama.service; - - -import com.kama.pojo.User; - -/** - * @InterfaceName UserService - * @Description 接口 - * @Author Tong - * @LastChangeDate 2024-12-05 0:52 - * @Version v1.0 - */ - -public interface UserService { - // 查询 - User getUserByUserId(Integer id); - // 新增 - Integer insertUserId(User user); -} diff --git a/version5/krpc-api/target/classes/com/kama/pojo/User$UserBuilder.class b/version5/krpc-api/target/classes/com/kama/pojo/User$UserBuilder.class deleted file mode 100644 index 261a629..0000000 Binary files a/version5/krpc-api/target/classes/com/kama/pojo/User$UserBuilder.class and /dev/null differ diff --git a/version5/krpc-api/target/classes/com/kama/pojo/User.class b/version5/krpc-api/target/classes/com/kama/pojo/User.class deleted file mode 100644 index 1dc838d..0000000 Binary files a/version5/krpc-api/target/classes/com/kama/pojo/User.class and /dev/null differ diff --git a/version5/krpc-api/target/classes/com/kama/service/UserService.class b/version5/krpc-api/target/classes/com/kama/service/UserService.class deleted file mode 100644 index b95b247..0000000 Binary files a/version5/krpc-api/target/classes/com/kama/service/UserService.class and /dev/null differ diff --git a/version5/krpc-api/target/krpc-api-1.0-SNAPSHOT.jar b/version5/krpc-api/target/krpc-api-1.0-SNAPSHOT.jar deleted file mode 100644 index 6cbcde5..0000000 Binary files a/version5/krpc-api/target/krpc-api-1.0-SNAPSHOT.jar and /dev/null differ diff --git a/version5/krpc-api/target/maven-archiver/pom.properties b/version5/krpc-api/target/maven-archiver/pom.properties deleted file mode 100644 index 243e555..0000000 --- a/version5/krpc-api/target/maven-archiver/pom.properties +++ /dev/null @@ -1,5 +0,0 @@ -#Generated by Maven -#Thu Dec 05 15:18:25 CST 2024 -groupId=com.kama -artifactId=krpc-api -version=1.0-SNAPSHOT diff --git a/version5/krpc-api/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst b/version5/krpc-api/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst deleted file mode 100644 index bf00c34..0000000 --- a/version5/krpc-api/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst +++ /dev/null @@ -1,3 +0,0 @@ -com\kama\pojo\User$UserBuilder.class -com\kama\pojo\User.class -com\kama\service\UserService.class diff --git a/version5/krpc-api/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst b/version5/krpc-api/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst deleted file mode 100644 index f327769..0000000 --- a/version5/krpc-api/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst +++ /dev/null @@ -1,2 +0,0 @@ -D:\java_stduy\version5\krpc-api\src\main\java\com\kama\pojo\User.java -D:\java_stduy\version5\krpc-api\src\main\java\com\kama\service\UserService.java diff --git a/version5/krpc-common/pom.xml b/version5/krpc-common/pom.xml deleted file mode 100644 index 9434747..0000000 --- a/version5/krpc-common/pom.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - 4.0.0 - - com.kama - version5 - 1.0-SNAPSHOT - - - krpc-common - - - com.kama - krpc-api - 1.0-SNAPSHOT - - - cn.hutool - hutool-all - 5.8.10 - compile - - - - 17 - 17 - UTF-8 - - - \ No newline at end of file diff --git a/version5/krpc-common/src/main/java/common/exception/SerializeException.java b/version5/krpc-common/src/main/java/common/exception/SerializeException.java deleted file mode 100644 index 33a75a5..0000000 --- a/version5/krpc-common/src/main/java/common/exception/SerializeException.java +++ /dev/null @@ -1,17 +0,0 @@ -package common.exception; - -/** - * @ClassName SerializeException - * @Description ToDo - * @Author Tong - * @LastChangeDate 2024-12-02 19:18 - * @Version v1.0 - */ -public class SerializeException extends RuntimeException{ - public SerializeException(String message) { - super(message); - } - public SerializeException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/version5/krpc-common/src/main/java/common/message/MessageType.java b/version5/krpc-common/src/main/java/common/message/MessageType.java deleted file mode 100644 index 51f44c0..0000000 --- a/version5/krpc-common/src/main/java/common/message/MessageType.java +++ /dev/null @@ -1,13 +0,0 @@ -package common.message; - -import lombok.AllArgsConstructor; - -@AllArgsConstructor -public enum MessageType { - REQUEST(0), RESPONSE(1); - private int code; - - public int getCode() { - return code; - } -} diff --git a/version5/krpc-common/src/main/java/common/message/RpcRequest.java b/version5/krpc-common/src/main/java/common/message/RpcRequest.java deleted file mode 100644 index b44a931..0000000 --- a/version5/krpc-common/src/main/java/common/message/RpcRequest.java +++ /dev/null @@ -1,31 +0,0 @@ -package common.message; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.io.Serializable; - -/** - * @ClassName RpcRequest - * @Description 定义请求消息格式 - * @Author Tong - * @LastChangeDate 2024-11-29 10:12 - * @Version v5.0 - */ - -@NoArgsConstructor -@AllArgsConstructor -@Data -@Builder -public class RpcRequest implements Serializable { - //接口名、方法名、参数列表参数类型 - private String interfaceName; - - private String methodName; - - private Object[] params; - - private Class[] paramsType; -} diff --git a/version5/krpc-common/src/main/java/common/message/RpcResponse.java b/version5/krpc-common/src/main/java/common/message/RpcResponse.java deleted file mode 100644 index 3d0fc81..0000000 --- a/version5/krpc-common/src/main/java/common/message/RpcResponse.java +++ /dev/null @@ -1,37 +0,0 @@ -package common.message; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.io.Serializable; - -/** - * @ClassName RpcResponse - * @Description 定义响应消息格式 - * @Author Tong - * @LastChangeDate 2024-11-29 10:14 - * @Version v5.0 - */ -@NoArgsConstructor -@AllArgsConstructor -@Data -@Builder -public class RpcResponse implements Serializable { - //状态信息 - private int code; - private String message; - //更新:加入传输数据的类型,以便在自定义序列化器中解析 - private Class dataType; - //具体数据 - private Object data; - - public static RpcResponse sussess(Object data) { - return RpcResponse.builder().code(200).dataType(data.getClass()).data(data).build(); - } - - public static RpcResponse fail(String msg) { - return RpcResponse.builder().code(500).message(msg).build(); - } -} diff --git a/version5/krpc-common/src/main/java/common/serializer/mycoder/MyDecoder.java b/version5/krpc-common/src/main/java/common/serializer/mycoder/MyDecoder.java deleted file mode 100644 index 16c2d26..0000000 --- a/version5/krpc-common/src/main/java/common/serializer/mycoder/MyDecoder.java +++ /dev/null @@ -1,58 +0,0 @@ -package common.serializer.mycoder; - - -import common.exception.SerializeException; -import common.message.MessageType; -import common.serializer.myserializer.Serializer; -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.ByteToMessageDecoder; -import lombok.extern.slf4j.Slf4j; - -import java.util.Arrays; -import java.util.List; - -/** - * @ClassName MyDecoder - * @Description 解码器 - * @Author Tong - * @LastChangeDate 2024-11-29 10:32 - * @Version v5.0 - */ -@Slf4j -public class MyDecoder extends ByteToMessageDecoder { - @Override - protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List out) throws Exception { - //检查可读字节数 - if (in.readableBytes() < 6) { // messageType + serializerType + length - return; - } - //1.读取消息类型 - short messageType = in.readShort(); - // 现在还只支持request与response请求 - if (messageType != MessageType.REQUEST.getCode() && - messageType != MessageType.RESPONSE.getCode()) { - log.warn("暂不支持此种数据, messageType: {}", messageType); - return; - } - //2.读取序列化的方式&类型 - short serializerType = in.readShort(); - Serializer serializer = Serializer.getSerializerByCode(serializerType); - if (serializer == null) { - log.error("不存在对应的序列化器, serializerType: {}", serializerType); - throw new SerializeException("不存在对应的序列化器, serializerType: " + serializerType); - } - //3.读取序列化数组长度 - int length = in.readInt(); - if (in.readableBytes() < length) { - return; // 数据不完整,等待更多数据 - } - //4.读取序列化数组 - byte[] bytes = new byte[length]; - in.readBytes(bytes); - log.debug("Received bytes: {}", Arrays.toString(bytes)); - Object deserialize = serializer.deserialize(bytes, messageType); - - out.add(deserialize); - } -} diff --git a/version5/krpc-common/src/main/java/common/serializer/mycoder/MyEncoder.java b/version5/krpc-common/src/main/java/common/serializer/mycoder/MyEncoder.java deleted file mode 100644 index 862796f..0000000 --- a/version5/krpc-common/src/main/java/common/serializer/mycoder/MyEncoder.java +++ /dev/null @@ -1,50 +0,0 @@ -package common.serializer.mycoder; - - -import common.message.MessageType; -import common.message.RpcRequest; -import common.message.RpcResponse; -import common.serializer.myserializer.Serializer; -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.MessageToByteEncoder; -import lombok.AllArgsConstructor; -import lombok.extern.slf4j.Slf4j; - -/** - * @ClassName MyEncoder - * @Description 编码器 - * @Author Tong - * @LastChangeDate 2024-11-29 10:32 - * @Version v5.0 - */ -@Slf4j -@AllArgsConstructor -public class MyEncoder extends MessageToByteEncoder { - private Serializer serializer; - - @Override - protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception { - log.debug("Encoding message of type: {}", msg.getClass()); - //1.写入消息类型 - if (msg instanceof RpcRequest) { - out.writeShort(MessageType.REQUEST.getCode()); - } else if (msg instanceof RpcResponse) { - out.writeShort(MessageType.RESPONSE.getCode()); - } else { - log.error("Unknown message type: {}", msg.getClass()); - throw new IllegalArgumentException("Unknown message type: " + msg.getClass()); - } - //2.写入序列化方式 - out.writeShort(serializer.getType()); - //得到序列化数组 - byte[] serializeBytes = serializer.serialize(msg); - if (serializeBytes == null || serializeBytes.length == 0) { - throw new IllegalArgumentException("Serialized message is empty"); - } - //3.写入长度 - out.writeInt(serializeBytes.length); - //4.写入序列化数组 - out.writeBytes(serializeBytes); - } -} diff --git a/version5/krpc-common/src/main/java/common/serializer/myserializer/HessianSerializer.java b/version5/krpc-common/src/main/java/common/serializer/myserializer/HessianSerializer.java deleted file mode 100644 index c30c14d..0000000 --- a/version5/krpc-common/src/main/java/common/serializer/myserializer/HessianSerializer.java +++ /dev/null @@ -1,52 +0,0 @@ -package common.serializer.myserializer; - -import com.caucho.hessian.io.HessianInput; -import com.caucho.hessian.io.HessianOutput; -import common.exception.SerializeException; - - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -/** - * @ClassName HessianSerializer - * @Description Hessian序列化 - * @Author Tong - * @LastChangeDate 2024-11-29 11:49 - * @Version v5.0 - */ -public class HessianSerializer implements Serializer { - @Override - public byte[] serialize(Object obj) { - // 使用 ByteArrayOutputStream 和 HessianOutput 来实现对象的序列化 - try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) { - HessianOutput hessianOutput = new HessianOutput(byteArrayOutputStream); - hessianOutput.writeObject(obj); // 将对象写入输出流 - return byteArrayOutputStream.toByteArray(); // 返回字节数组 - } catch (IOException e) { - throw new SerializeException("Serialization failed"); - } - } - - @Override - public Object deserialize(byte[] bytes, int messageType) { - // 使用 ByteArrayInputStream 和 HessianInput 来实现反序列化 - try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes)) { - HessianInput hessianInput = new HessianInput(byteArrayInputStream); - return hessianInput.readObject(); // 读取并返回对象 - } catch (IOException e) { - throw new SerializeException("Deserialization failed"); - } - } - - @Override - public int getType() { - return 3; - } - - @Override - public String toString() { - return "Hessian"; - } -} \ No newline at end of file diff --git a/version5/krpc-common/src/main/java/common/serializer/myserializer/JsonSerializer.java b/version5/krpc-common/src/main/java/common/serializer/myserializer/JsonSerializer.java deleted file mode 100644 index fab6b97..0000000 --- a/version5/krpc-common/src/main/java/common/serializer/myserializer/JsonSerializer.java +++ /dev/null @@ -1,78 +0,0 @@ -package common.serializer.myserializer; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import common.message.RpcRequest; -import common.message.RpcResponse; - - -/** - * @ClassName JsonSerializer - * @Description json序列化 - * @Author Tong - * @LastChangeDate 2024-11-29 10:33 - * @Version v5.0 - */ -public class JsonSerializer implements Serializer { - @Override - public byte[] serialize(Object obj) { - byte[] bytes = JSONObject.toJSONBytes(obj); - return bytes; - } - - @Override - public Object deserialize(byte[] bytes, int messageType) { - Object obj = null; - // 传输的消息分为request与response - switch (messageType){ - case 0: - RpcRequest request = JSON.parseObject(bytes, RpcRequest.class); - Object[] objects = new Object[request.getParams().length]; - // 把json字串转化成对应的对象, fastjson可以读出基本数据类型,不用转化 - // 对转换后的request中的params属性逐个进行类型判断 - for(int i = 0; i < objects.length; i++){ - Class paramsType = request.getParamsType()[i]; - //判断每个对象类型是否和paramsTypes中的一致 - if (!paramsType.isAssignableFrom(request.getParams()[i].getClass())){ - //如果不一致,就行进行类型转换 - objects[i] = JSONObject.toJavaObject((JSONObject) request.getParams()[i],request.getParamsType()[i]); - }else{ - //如果一致就直接赋给objects[i] - objects[i] = request.getParams()[i]; - } - } - request.setParams(objects); - obj = request; - break; - case 1: - RpcResponse response = JSON.parseObject(bytes, RpcResponse.class); - // 如果类型为空,说明返回错误 - if(response.getDataType()==null){ - obj = RpcResponse.fail("类型为空"); - break; - } - Class dataType = response.getDataType(); - //判断转化后的response对象中的data的类型是否正确 - if(!dataType.isAssignableFrom(response.getData().getClass())){ - response.setData(JSONObject.toJavaObject((JSONObject) response.getData(),dataType)); - } - obj = response; - break; - default: - System.out.println("暂时不支持此种消息"); - throw new RuntimeException(); - } - return obj; - } - - //1 代表json序列化方式 - @Override - public int getType() { - return 1; - } - - @Override - public String toString() { - return "Json"; - } -} diff --git a/version5/krpc-common/src/main/java/common/serializer/myserializer/KryoSerializer.java b/version5/krpc-common/src/main/java/common/serializer/myserializer/KryoSerializer.java deleted file mode 100644 index 9c6ae18..0000000 --- a/version5/krpc-common/src/main/java/common/serializer/myserializer/KryoSerializer.java +++ /dev/null @@ -1,81 +0,0 @@ -package common.serializer.myserializer; - -import com.esotericsoftware.kryo.Kryo; -import com.esotericsoftware.kryo.io.Input; -import com.esotericsoftware.kryo.io.Output; - -import com.kama.pojo.User; -import common.exception.SerializeException; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; - - -/** - * @ClassName KryoSerializer - * @Description kryo序列化 - * @Author Tong - * @LastChangeDate 2024-11-29 11:29 - * @Version v5.0 - */ - -public class KryoSerializer implements Serializer { - private Kryo kryo; - - public KryoSerializer() { - this.kryo = new Kryo(); - } - - @Override - public byte[] serialize(Object obj) { - if (obj == null) { - throw new IllegalArgumentException("Cannot serialize null object"); - } - - try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - Output output = new Output(byteArrayOutputStream)) { - - kryo.writeObject(output, obj); // 使用 Kryo 写入对象 - return output.toBytes(); // 返回字节数组 - - } catch (Exception e) { - throw new SerializeException("Serialization failed"); - } - } - - @Override - public Object deserialize(byte[] bytes, int messageType) { - if (bytes == null || bytes.length == 0) { - throw new IllegalArgumentException("Cannot deserialize null or empty byte array"); - } - - try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); - Input input = new Input(byteArrayInputStream)) { - - // 根据 messageType 来反序列化不同的类 - Class clazz = getClassForMessageType(messageType); - return kryo.readObject(input, clazz); // 使用 Kryo 反序列化对象 - - } catch (Exception e) { - throw new SerializeException("Deserialization failed"); - } - } - - @Override - public int getType() { - return 2; - } - - private Class getClassForMessageType(int messageType) { - if (messageType == 1) { - return User.class; // 假设我们在此反序列化成 User 类 - } else { - throw new SerializeException("Unknown message type: " + messageType); - } - } - - @Override - public String toString() { - return "Kryo"; - } -} \ No newline at end of file diff --git a/version5/krpc-common/src/main/java/common/serializer/myserializer/ObjectSerializer.java b/version5/krpc-common/src/main/java/common/serializer/myserializer/ObjectSerializer.java deleted file mode 100644 index eaf13c0..0000000 --- a/version5/krpc-common/src/main/java/common/serializer/myserializer/ObjectSerializer.java +++ /dev/null @@ -1,60 +0,0 @@ -package common.serializer.myserializer; - -import java.io.*; - -/** - * @ClassName ObjectSerializer - * @Description JDK序列化方式 - * @Author Tong - * @LastChangeDate 2024-11-29 10:34 - * @Version v5.0 - */ -public class ObjectSerializer implements Serializer { - //利用Java io 对象 -》字节数组 - @Override - public byte[] serialize(Object obj) { - byte[] bytes=null; - ByteArrayOutputStream bos=new ByteArrayOutputStream(); - try { - //是一个对象输出流,用于将 Java 对象序列化为字节流,并将其连接到bos上 - ObjectOutputStream oos = new ObjectOutputStream(bos); - oos.writeObject(obj); - //刷新 ObjectOutputStream,确保所有缓冲区中的数据都被写入到底层流中。 - oos.flush(); - //将bos其内部缓冲区中的数据转换为字节数组 - bytes = bos.toByteArray(); - oos.close(); - bos.close(); - } catch (IOException e) { - e.printStackTrace(); - } - return bytes; - } - - //字节数组 -》对象 - @Override - public Object deserialize(byte[] bytes, int messageType) { - Object obj = null; - ByteArrayInputStream bis = new ByteArrayInputStream(bytes); - try { - ObjectInputStream ois = new ObjectInputStream(bis); - obj = ois.readObject(); - ois.close(); - bis.close(); - } catch (IOException | ClassNotFoundException e) { - e.printStackTrace(); - } - return obj; - } - - //0 代表Java 原生序列器 - @Override - public int getType() { - return 0; - } - - @Override - public String toString() { - return "JDK"; - } -} \ No newline at end of file diff --git a/version5/krpc-common/src/main/java/common/serializer/myserializer/ProtostuffSerializer.java b/version5/krpc-common/src/main/java/common/serializer/myserializer/ProtostuffSerializer.java deleted file mode 100644 index dd97db2..0000000 --- a/version5/krpc-common/src/main/java/common/serializer/myserializer/ProtostuffSerializer.java +++ /dev/null @@ -1,83 +0,0 @@ -package common.serializer.myserializer; - - -import com.kama.pojo.User; -import common.exception.SerializeException; -import io.protostuff.LinkedBuffer; -import io.protostuff.ProtostuffIOUtil; -import io.protostuff.Schema; -import io.protostuff.runtime.RuntimeSchema; -/** - * @ClassName ProtostuffSerializer - * @Description protostuff序列化 - * @Author Tong - * @LastChangeDate 2024-11-29 11:55 - * @Version v5.0 - */ -public class ProtostuffSerializer implements Serializer { - - @Override - public byte[] serialize(Object obj) { - // 检查 null 对象 - if (obj == null) { - throw new IllegalArgumentException("Cannot serialize null object"); - } - // 获取对象的 schema - Schema schema = RuntimeSchema.getSchema(obj.getClass()); - - // 使用 LinkedBuffer 来创建缓冲区(默认大小 1024) - LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE); - // 序列化对象为字节数组 - byte[] bytes; - try { - bytes = ProtostuffIOUtil.toByteArray(obj, schema, buffer); - } finally { - buffer.clear(); - } - return bytes; - } - - @Override - public Object deserialize(byte[] bytes, int messageType) { - if (bytes == null || bytes.length == 0) { - throw new IllegalArgumentException("Cannot deserialize null or empty byte array"); - } - - // 根据 messageType 来决定反序列化的类,这里假设 `messageType` 是类的标识符 - Class clazz = getClassForMessageType(messageType); - - // 获取对象的 schema - Schema schema = RuntimeSchema.getSchema(clazz); - - // 创建一个空的对象实例 - Object obj; - try { - obj = clazz.getDeclaredConstructor().newInstance(); - } catch (Exception e) { - throw new SerializeException("Deserialization failed due to reflection issues"); - } - - // 反序列化字节数组为对象 - ProtostuffIOUtil.mergeFrom(bytes, obj, schema); - return obj; - } - - @Override - public int getType() { - return 4; - } - - // 用于根据 messageType 获取对应的类 - private Class getClassForMessageType(int messageType) { - if (messageType == 1) { - return User.class; // 假设我们在此反序列化成 User 类 - } else { - throw new SerializeException("Unknown message type: " + messageType); - } - } - - @Override - public String toString() { - return "Protostuff"; - } -} diff --git a/version5/krpc-common/src/main/java/common/serializer/myserializer/Serializer.java b/version5/krpc-common/src/main/java/common/serializer/myserializer/Serializer.java deleted file mode 100644 index eb4b097..0000000 --- a/version5/krpc-common/src/main/java/common/serializer/myserializer/Serializer.java +++ /dev/null @@ -1,35 +0,0 @@ -package common.serializer.myserializer; - - - - -import java.util.HashMap; -import java.util.Map; - -/** - * @InterfaceName Serializer - * @Description 序列化接口 - * @Author Tong - * @LastChangeDate 2024-11-29 10:33 - * @Version v5.0 - */ -public interface Serializer { - byte[] serialize(Object obj); - - Object deserialize(byte[] bytes, int messageType); - - int getType(); - - // 使用 Map 存储序列化器 - static Serializer getSerializerByCode(int code) { - // 静态映射,保证只初始化一次 - Map serializerMap = new HashMap<>(); - serializerMap.put(0, new ObjectSerializer()); - serializerMap.put(1, new JsonSerializer()); - serializerMap.put(2, new KryoSerializer()); - serializerMap.put(3, new HessianSerializer()); - serializerMap.put(4, new ProtostuffSerializer()); - - return serializerMap.get(code); // 如果不存在,则返回 null - } -} diff --git a/version5/krpc-common/src/main/java/common/spi/SpiLoader.java b/version5/krpc-common/src/main/java/common/spi/SpiLoader.java deleted file mode 100644 index e6a5ab9..0000000 --- a/version5/krpc-common/src/main/java/common/spi/SpiLoader.java +++ /dev/null @@ -1,111 +0,0 @@ -package common.spi; - - -import cn.hutool.core.io.resource.ResourceUtil; -import common.serializer.myserializer.Serializer; -import lombok.extern.slf4j.Slf4j; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.URL; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * @ClassName SpiLoader - * @Description spi实现 - * @Author Tong - * @LastChangeDate 2024-12-05 14:53 - * @Version v5.0 - */ -@Slf4j -public class SpiLoader { - - // 存储已加载的 SPI 实现类的映射 - private static final Map>> loadedSpiMap = new ConcurrentHashMap<>(); - - // 缓存实例,避免重复实例化 - private static final Map instanceCache = new ConcurrentHashMap<>(); - - // SPI 配置文件的路径 - private static final String SPI_CONFIG_DIR = "META-INF/serializer/"; - - /** - * 加载指定接口的 SPI 实现类 - * - * @param serviceInterface 接口类 - */ - public static void loadSpi(Class serviceInterface) { - String interfaceName = serviceInterface.getName(); - - // 如果已经加载过该接口的 SPI 实现,直接返回 - if (loadedSpiMap.containsKey(interfaceName)) { - return; - } - - Map> keyClassMap = new HashMap<>(); - - // 读取配置文件,获取所有实现类 - List resources = ResourceUtil.getResources(SPI_CONFIG_DIR + serviceInterface.getName()); - for (URL resource : resources) { - try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource.openStream()))) { - String line; - while ((line = reader.readLine()) != null) { - if (!line.trim().isEmpty() && !line.startsWith("#")) { - String[] parts = line.split("="); - if (parts.length == 2) { - String key = parts[0].trim(); - String className = parts[1].trim(); - Class implClass = Class.forName(className); - if (serviceInterface.isAssignableFrom(implClass)) { - keyClassMap.put(key, (Class) implClass); - } - } - } - } - } catch (IOException | ClassNotFoundException e) { - log.error("Failed to load SPI resource: " + resource, e); - } - } - - // 将该接口的 SPI 实现类存入缓存 - loadedSpiMap.put(interfaceName, keyClassMap); - } - - /** - * 根据接口和 key 获取 SPI 实现类实例 - * - * @param serviceInterface 接口类 - * @param key 序列化器的 key - * @param 接口类型 - * @return 对应的 SPI 实现类实例 - */ - public static T getInstance(Class serviceInterface, String key) { - String interfaceName = serviceInterface.getName(); - Map> keyClassMap = loadedSpiMap.get(interfaceName); - - if (keyClassMap == null) { - throw new RuntimeException("SPI not loaded for " + interfaceName); - } - - Class implClass = keyClassMap.get(key); - if (implClass == null) { - throw new RuntimeException("No SPI implementation found for key " + key); - } - - // 从缓存中获取实例,如果不存在则创建 - String implClassName = implClass.getName(); - if (!instanceCache.containsKey(implClassName)) { - try { - instanceCache.put(implClassName, implClass.newInstance()); - } catch (InstantiationException | IllegalAccessException e) { - throw new RuntimeException("Failed to instantiate SPI implementation: " + implClassName, e); - } - } - - return (T) instanceCache.get(implClassName); - } -} diff --git a/version5/krpc-common/src/main/java/common/util/ConfigUtil.java b/version5/krpc-common/src/main/java/common/util/ConfigUtil.java deleted file mode 100644 index 8be9a00..0000000 --- a/version5/krpc-common/src/main/java/common/util/ConfigUtil.java +++ /dev/null @@ -1,48 +0,0 @@ -package common.util; - -import cn.hutool.core.util.StrUtil; -import cn.hutool.setting.dialect.Props; -import lombok.extern.slf4j.Slf4j; - -/** - * @ClassName ConfigUtil - * @Description 工具 - * @Author Tong - * @LastChangeDate 2024-12-05 11:12 - * @Version v5.0 - */ -@Slf4j -public class ConfigUtil { - - // 加载配置文件,使用默认环境 - public static T loadConfig(Class targetClass, String prefix) { - return loadConfig(targetClass, prefix, ""); - } - - // 加载配置文件,支持指定环境 - public static T loadConfig(Class targetClass, String prefix, String environment) { - StringBuilder configFileNameBuilder = new StringBuilder("application"); - - if (StrUtil.isNotBlank(environment)) { - configFileNameBuilder.append("-").append(environment); - } - configFileNameBuilder.append(".properties"); - - // 加载配置文件 - Props properties = new Props(configFileNameBuilder.toString()); - - if (properties.isEmpty()) { - log.warn("配置文件 '{}' 为空或加载失败!", configFileNameBuilder.toString()); - } else { - log.info("加载配置文件: '{}'", configFileNameBuilder.toString()); - } - - // 返回转化后的配置对象 - try { - return properties.toBean(targetClass, prefix); - } catch (Exception e) { - log.error("配置转换失败,目标类: {}", targetClass.getName(), e); - throw new RuntimeException("配置加载失败", e); - } - } -} diff --git a/version5/krpc-common/target/classes/common/exception/SerializeException.class b/version5/krpc-common/target/classes/common/exception/SerializeException.class deleted file mode 100644 index a4b8bf6..0000000 Binary files a/version5/krpc-common/target/classes/common/exception/SerializeException.class and /dev/null differ diff --git a/version5/krpc-common/target/classes/common/message/MessageType.class b/version5/krpc-common/target/classes/common/message/MessageType.class deleted file mode 100644 index 6f92c64..0000000 Binary files a/version5/krpc-common/target/classes/common/message/MessageType.class and /dev/null differ diff --git a/version5/krpc-common/target/classes/common/message/RpcRequest$RpcRequestBuilder.class b/version5/krpc-common/target/classes/common/message/RpcRequest$RpcRequestBuilder.class deleted file mode 100644 index f5d58a6..0000000 Binary files a/version5/krpc-common/target/classes/common/message/RpcRequest$RpcRequestBuilder.class and /dev/null differ diff --git a/version5/krpc-common/target/classes/common/message/RpcRequest.class b/version5/krpc-common/target/classes/common/message/RpcRequest.class deleted file mode 100644 index 6f24559..0000000 Binary files a/version5/krpc-common/target/classes/common/message/RpcRequest.class and /dev/null differ diff --git a/version5/krpc-common/target/classes/common/message/RpcResponse$RpcResponseBuilder.class b/version5/krpc-common/target/classes/common/message/RpcResponse$RpcResponseBuilder.class deleted file mode 100644 index 8bfe3b5..0000000 Binary files a/version5/krpc-common/target/classes/common/message/RpcResponse$RpcResponseBuilder.class and /dev/null differ diff --git a/version5/krpc-common/target/classes/common/message/RpcResponse.class b/version5/krpc-common/target/classes/common/message/RpcResponse.class deleted file mode 100644 index 9a501b9..0000000 Binary files a/version5/krpc-common/target/classes/common/message/RpcResponse.class and /dev/null differ diff --git a/version5/krpc-common/target/classes/common/serializer/mycoder/MyDecoder.class b/version5/krpc-common/target/classes/common/serializer/mycoder/MyDecoder.class deleted file mode 100644 index 44eb61a..0000000 Binary files a/version5/krpc-common/target/classes/common/serializer/mycoder/MyDecoder.class and /dev/null differ diff --git a/version5/krpc-common/target/classes/common/serializer/mycoder/MyEncoder.class b/version5/krpc-common/target/classes/common/serializer/mycoder/MyEncoder.class deleted file mode 100644 index cbdc4b0..0000000 Binary files a/version5/krpc-common/target/classes/common/serializer/mycoder/MyEncoder.class and /dev/null differ diff --git a/version5/krpc-common/target/classes/common/serializer/myserializer/HessianSerializer.class b/version5/krpc-common/target/classes/common/serializer/myserializer/HessianSerializer.class deleted file mode 100644 index e54e9e9..0000000 Binary files a/version5/krpc-common/target/classes/common/serializer/myserializer/HessianSerializer.class and /dev/null differ diff --git a/version5/krpc-common/target/classes/common/serializer/myserializer/JsonSerializer.class b/version5/krpc-common/target/classes/common/serializer/myserializer/JsonSerializer.class deleted file mode 100644 index a9726a3..0000000 Binary files a/version5/krpc-common/target/classes/common/serializer/myserializer/JsonSerializer.class and /dev/null differ diff --git a/version5/krpc-common/target/classes/common/serializer/myserializer/KryoSerializer.class b/version5/krpc-common/target/classes/common/serializer/myserializer/KryoSerializer.class deleted file mode 100644 index f10abef..0000000 Binary files a/version5/krpc-common/target/classes/common/serializer/myserializer/KryoSerializer.class and /dev/null differ diff --git a/version5/krpc-common/target/classes/common/serializer/myserializer/ObjectSerializer.class b/version5/krpc-common/target/classes/common/serializer/myserializer/ObjectSerializer.class deleted file mode 100644 index b7b8e5e..0000000 Binary files a/version5/krpc-common/target/classes/common/serializer/myserializer/ObjectSerializer.class and /dev/null differ diff --git a/version5/krpc-common/target/classes/common/serializer/myserializer/ProtostuffSerializer.class b/version5/krpc-common/target/classes/common/serializer/myserializer/ProtostuffSerializer.class deleted file mode 100644 index 8cf83ad..0000000 Binary files a/version5/krpc-common/target/classes/common/serializer/myserializer/ProtostuffSerializer.class and /dev/null differ diff --git a/version5/krpc-common/target/classes/common/serializer/myserializer/Serializer.class b/version5/krpc-common/target/classes/common/serializer/myserializer/Serializer.class deleted file mode 100644 index 4285b7e..0000000 Binary files a/version5/krpc-common/target/classes/common/serializer/myserializer/Serializer.class and /dev/null differ diff --git a/version5/krpc-common/target/classes/common/spi/SpiLoader.class b/version5/krpc-common/target/classes/common/spi/SpiLoader.class deleted file mode 100644 index f8829d4..0000000 Binary files a/version5/krpc-common/target/classes/common/spi/SpiLoader.class and /dev/null differ diff --git a/version5/krpc-common/target/classes/common/util/ConfigUtil.class b/version5/krpc-common/target/classes/common/util/ConfigUtil.class deleted file mode 100644 index 7fb5901..0000000 Binary files a/version5/krpc-common/target/classes/common/util/ConfigUtil.class and /dev/null differ diff --git a/version5/krpc-consumer/pom.xml b/version5/krpc-consumer/pom.xml deleted file mode 100644 index a9dbd99..0000000 --- a/version5/krpc-consumer/pom.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - 4.0.0 - - com.kama - version5 - 1.0-SNAPSHOT - - - krpc-consumer - - - 17 - 17 - UTF-8 - - - - org.springframework.boot - spring-boot-starter-web - RELEASE - compile - - - com.kama - krpc-api - 1.0-SNAPSHOT - compile - - - com.kama - krpc-common - 1.0-SNAPSHOT - - - com.kama - krpc-core - 1.0-SNAPSHOT - - - cn.hutool - hutool-all - 5.8.10 - - - - \ No newline at end of file diff --git a/version5/krpc-consumer/src/main/java/com/kama/consumer/ConsumerTest.java b/version5/krpc-consumer/src/main/java/com/kama/consumer/ConsumerTest.java deleted file mode 100644 index c04606a..0000000 --- a/version5/krpc-consumer/src/main/java/com/kama/consumer/ConsumerTest.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.kama.consumer; - -import com.kama.client.proxy.ClientProxy; -import com.kama.pojo.User; - -import com.kama.service.UserService; -import lombok.extern.slf4j.Slf4j; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -/** - * @ClassName ConsumerExample - * @Description 客户端测试 - * @Author Tong - * @LastChangeDate 2024-12-05 16:20 - * @Version v5.0 - */ -@Slf4j -public class ConsumerTest { - - private static final int THREAD_POOL_SIZE = 20; - private static final ExecutorService executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE); - - public static void main(String[] args) throws InterruptedException { - ClientProxy clientProxy = new ClientProxy(); - UserService proxy = clientProxy.getProxy(UserService.class); - for (int i = 0; i < 120; i++) { - final Integer i1 = i; - if (i % 30 == 0) { - // Simulate delay for every 30 requests - Thread.sleep(10000); - } - - // Submit tasks to executor service (thread pool) - executorService.submit(() -> { - try { - User user = proxy.getUserByUserId(i1); - if (user != null) { - log.info("从服务端得到的user={}", user); - } else { - log.warn("获取的 user 为 null, userId={}", i1); - } - - Integer id = proxy.insertUserId(User.builder() - .id(i1) - .userName("User" + i1) - .gender(true) - .build()); - - if (id != null) { - log.info("向服务端插入user的id={}", id); - } else { - log.warn("插入失败,返回的id为null, userId={}", i1); - } - } catch (Exception e) { - log.error("调用服务时发生异常,userId={}", i1, e); - } - }); - } - - // Gracefully shutdown the executor service - executorService.shutdown(); - } - -} diff --git a/version5/krpc-consumer/src/main/java/com/kama/consumer/ConsumerTestConfig.java b/version5/krpc-consumer/src/main/java/com/kama/consumer/ConsumerTestConfig.java deleted file mode 100644 index b816281..0000000 --- a/version5/krpc-consumer/src/main/java/com/kama/consumer/ConsumerTestConfig.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.kama.consumer; - - -import com.kama.config.KRpcConfig; -import common.util.ConfigUtil; - -/** - * @ClassName ConsumerTestConfig - * @Description 测试配置顶 - * @Author Tong - * @LastChangeDate 2024-12-05 11:29 - * @Version v1.0 - */ -public class ConsumerTestConfig { - public static void main(String[] args) { - KRpcConfig rpc = ConfigUtil.loadConfig(KRpcConfig.class, "rpc"); - System.out.println(rpc); - } - -} diff --git a/version5/krpc-consumer/src/main/resources/application.properties b/version5/krpc-consumer/src/main/resources/application.properties deleted file mode 100644 index e784008..0000000 --- a/version5/krpc-consumer/src/main/resources/application.properties +++ /dev/null @@ -1,7 +0,0 @@ -rpc.name=krpc -rpc.version=1.0.0 -rpc.port=9999 -rpc.serializer=Hessian -rpc.host=localhost -rpc.registry=zookeeper -rpc.loadBalance=ConsistencyHash \ No newline at end of file diff --git a/version5/krpc-consumer/target/classes/application.properties b/version5/krpc-consumer/target/classes/application.properties deleted file mode 100644 index e784008..0000000 --- a/version5/krpc-consumer/target/classes/application.properties +++ /dev/null @@ -1,7 +0,0 @@ -rpc.name=krpc -rpc.version=1.0.0 -rpc.port=9999 -rpc.serializer=Hessian -rpc.host=localhost -rpc.registry=zookeeper -rpc.loadBalance=ConsistencyHash \ No newline at end of file diff --git a/version5/krpc-consumer/target/classes/com/kama/consumer/ConsumerTest.class b/version5/krpc-consumer/target/classes/com/kama/consumer/ConsumerTest.class deleted file mode 100644 index 03a4c00..0000000 Binary files a/version5/krpc-consumer/target/classes/com/kama/consumer/ConsumerTest.class and /dev/null differ diff --git a/version5/krpc-consumer/target/classes/com/kama/consumer/ConsumerTestConfig.class b/version5/krpc-consumer/target/classes/com/kama/consumer/ConsumerTestConfig.class deleted file mode 100644 index 6517f51..0000000 Binary files a/version5/krpc-consumer/target/classes/com/kama/consumer/ConsumerTestConfig.class and /dev/null differ diff --git a/version5/krpc-consumer/target/krpc-consumer-1.0-SNAPSHOT.jar b/version5/krpc-consumer/target/krpc-consumer-1.0-SNAPSHOT.jar deleted file mode 100644 index a2d7d28..0000000 Binary files a/version5/krpc-consumer/target/krpc-consumer-1.0-SNAPSHOT.jar and /dev/null differ diff --git a/version5/krpc-consumer/target/maven-archiver/pom.properties b/version5/krpc-consumer/target/maven-archiver/pom.properties deleted file mode 100644 index 96d4f06..0000000 --- a/version5/krpc-consumer/target/maven-archiver/pom.properties +++ /dev/null @@ -1,5 +0,0 @@ -#Generated by Maven -#Thu Dec 05 15:19:00 CST 2024 -groupId=com.kama -artifactId=krpc-consumer -version=1.0-SNAPSHOT diff --git a/version5/krpc-consumer/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst b/version5/krpc-consumer/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst deleted file mode 100644 index e3ec4a4..0000000 --- a/version5/krpc-consumer/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst +++ /dev/null @@ -1,2 +0,0 @@ -com\kama\ConsumerTestConfig.class -com\kama\ConsumerApplication.class diff --git a/version5/krpc-consumer/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst b/version5/krpc-consumer/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst deleted file mode 100644 index 08a64ca..0000000 --- a/version5/krpc-consumer/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst +++ /dev/null @@ -1,2 +0,0 @@ -D:\java_stduy\version5\krpc-consumer\src\main\java\com\kama\ConsumerTestConfig.java -D:\java_stduy\version5\krpc-consumer\src\main\java\com\kama\ConsumerApplication.java diff --git a/version5/krpc-core/pom.xml b/version5/krpc-core/pom.xml deleted file mode 100644 index f0a7710..0000000 --- a/version5/krpc-core/pom.xml +++ /dev/null @@ -1,114 +0,0 @@ - - - 4.0.0 - - com.kama - version5 - 1.0-SNAPSHOT - - - krpc-core - - - 17 - 17 - UTF-8 - - - - com.kama - krpc-common - 1.0-SNAPSHOT - - - org.projectlombok - lombok - 1.18.30 - compile - - - io.netty - netty-all - 4.1.51.Final - compile - - - - org.apache.curator - curator-recipes - 5.1.0 - - - com.alibaba - fastjson - 1.2.83 - - - com.esotericsoftware - kryo - 4.0.2 - - - com.caucho - hessian - 4.0.66 - - - io.protostuff - protostuff-core - 1.7.4 - - - io.protostuff - protostuff-runtime - 1.7.4 - - - com.github.rholder - guava-retrying - 2.0.0 - - - org.jetbrains - annotations - 17.0.0 - compile - - - com.kama - krpc-api - 1.0-SNAPSHOT - - - cn.hutool - hutool-all - 5.8.10 - - - - org.junit.jupiter - junit-jupiter-api - 5.11.3 - test - - - org.junit.jupiter - junit-jupiter-engine - 5.11.3 - test - - - - org.junit.platform - junit-platform-launcher - 1.11.3 - test - - - junit - junit - - - \ No newline at end of file diff --git a/version5/krpc-core/src/main/java/com/kama/KRpcApplication.java b/version5/krpc-core/src/main/java/com/kama/KRpcApplication.java deleted file mode 100644 index 9529f74..0000000 --- a/version5/krpc-core/src/main/java/com/kama/KRpcApplication.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.kama; - - -import com.kama.config.KRpcConfig; -import com.kama.config.RpcConstant; -import common.util.ConfigUtil; -import lombok.extern.slf4j.Slf4j; - -/** - * @ClassName RpcApplication - * @Description 测试配置顶,学习更多参考Dubbo - * @Author Tong - * @LastChangeDate 2024-12-05 11:22 - * @Version v5.0 - */ -@Slf4j -public class KRpcApplication { - private static volatile KRpcConfig rpcConfigInstance; - - public static void initialize(KRpcConfig customRpcConfig) { - rpcConfigInstance = customRpcConfig; - log.info("RPC 框架初始化,配置 = {}", customRpcConfig); - } - - public static void initialize() { - KRpcConfig customRpcConfig; - try { - customRpcConfig = ConfigUtil.loadConfig(KRpcConfig.class, RpcConstant.CONFIG_FILE_PREFIX); - log.info("成功加载配置文件,配置文件名称 = {}", RpcConstant.CONFIG_FILE_PREFIX); // 添加成功加载的日志 - } catch (Exception e) { - // 配置加载失败,使用默认配置 - customRpcConfig = new KRpcConfig(); - log.warn("配置加载失败,使用默认配置"); - } - initialize(customRpcConfig); - } - - public static KRpcConfig getRpcConfig() { - if (rpcConfigInstance == null) { - synchronized (KRpcApplication.class) { - if (rpcConfigInstance == null) { - initialize(); // 确保在第一次调用时初始化 - } - } - } - return rpcConfigInstance; - } -} diff --git a/version5/krpc-core/src/main/java/com/kama/client/cache/ServiceCache.java b/version5/krpc-core/src/main/java/com/kama/client/cache/ServiceCache.java deleted file mode 100644 index 8eba240..0000000 --- a/version5/krpc-core/src/main/java/com/kama/client/cache/ServiceCache.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.kama.client.cache; - -import lombok.extern.slf4j.Slf4j; - -import java.util.ArrayList; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * @ClassName serviceCache - * @Description 建立本地缓存 - * @Author Tong - * @LastChangeDate 2024-12-02 10:34 - * @Version v5.0 - */ -@Slf4j -public class ServiceCache { - //key: serviceName 服务名 - //value: addressList 服务提供者列表 - private static Map> cache = new ConcurrentHashMap<>(); - - //添加服务 - public void addServiceToCache(String serviceName, String address) { - if (cache.containsKey(serviceName)) { - List addressList = cache.get(serviceName); - addressList.add(address); - log.info("有服务名情况,将name为{}和地址为{}的服务添加到本地缓存中", serviceName, address); - } else { - List addressList = new ArrayList<>(); - addressList.add(address); - cache.put(serviceName, addressList); - log.info("无服务名情况,将name为{}和地址为{}的服务添加到本地缓存中", serviceName, address); - } - } - - //修改服务地址 - public void replaceServiceAddress(String serviceName, String oldAddress, String newAddress) { - if (cache.containsKey(serviceName)) { - List addressList = cache.get(serviceName); - addressList.remove(oldAddress); - addressList.add(newAddress); - log.info("将服务{}的地址{}替换为{}", serviceName, oldAddress, newAddress); - } else { - log.error("旧地址{}不在服务{}的地址列表中", oldAddress, serviceName); - } - } - - //从缓存中取服务地址列表 - public List getServiceListFromCache(String serviceName) { - if (!cache.containsKey(serviceName)) { - log.warn("服务{}未找到", serviceName); - //返回个不可修改的空列表,避免调用的时候出现空指针异常 - return Collections.emptyList(); - } - return cache.get(serviceName); - } - - //从缓存中删除服务地址 - public void delete(String serviceName, String address) { - List addressList = cache.get(serviceName); - if (addressList != null && addressList.contains(address)) { - addressList.remove(address); - log.info("将name为{}和地址为{}的服务从本地缓存中删除", serviceName, address); - if (addressList.isEmpty()) { - cache.remove(serviceName); // 移除该服务的缓存条目 - log.info("服务{}的地址列表为空,已从缓存中清除", serviceName); - } - } else { - log.warn("删除失败,地址{}不在服务{}的地址列表中", address, serviceName); - } - } -} diff --git a/version5/krpc-core/src/main/java/com/kama/client/circuitbreaker/CircuitBreaker.java b/version5/krpc-core/src/main/java/com/kama/client/circuitbreaker/CircuitBreaker.java deleted file mode 100644 index 53a6489..0000000 --- a/version5/krpc-core/src/main/java/com/kama/client/circuitbreaker/CircuitBreaker.java +++ /dev/null @@ -1,109 +0,0 @@ -package com.kama.client.circuitbreaker; - -import lombok.extern.slf4j.Slf4j; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.concurrent.atomic.AtomicInteger; - -/** - * @ClassName CircuitBreaker - * @Description 熔断器的状态 - * @Author Tong - * @LastChangeDate 2024-12-02 10:45 - * @Version v5.0 - */ -@Slf4j -public class CircuitBreaker { - //当前状态 - private CircuitBreakerState state = CircuitBreakerState.CLOSED; - private AtomicInteger failureCount = new AtomicInteger(0); - private AtomicInteger successCount = new AtomicInteger(0); - private AtomicInteger requestCount = new AtomicInteger(0); - //失败次数阈值 - private final int failureThreshold; - //半开启-》关闭状态的成功次数比例 - private final double halfOpenSuccessRate; - //恢复时间 - private final long retryTimePeriod; - //上一次失败时间 - private long lastFailureTime = 0; - - public CircuitBreaker(int failureThreshold, double halfOpenSuccessRate, long retryTimePeriod) { - this.failureThreshold = failureThreshold; - this.halfOpenSuccessRate = halfOpenSuccessRate; - this.retryTimePeriod = retryTimePeriod; - } - - //查看当前熔断器是否允许请求通过 - public synchronized boolean allowRequest() { - long currentTime = System.currentTimeMillis(); - log.info("熔断前检查, 当前失败次数:{}", failureCount); - switch (state) { - case OPEN: - if (currentTime - lastFailureTime > retryTimePeriod) { - state = CircuitBreakerState.HALF_OPEN; - resetCounts(); - log.info("熔断已解除,进入半开启状态,允许请求通过"); - return true; - } - log.warn("熔断生效中,拒绝请求!"); - return false; - case HALF_OPEN: - requestCount.incrementAndGet(); - log.info("当前为半开启状态,计数请求"); - return true; - case CLOSED: - default: - log.info("当前为正常状态,允许请求通过"); - return true; - } - } - - //记录成功 - public synchronized void recordSuccess() { - if (state == CircuitBreakerState.HALF_OPEN) { - successCount.incrementAndGet(); - if (successCount.get() >= halfOpenSuccessRate * requestCount.get()) { - state = CircuitBreakerState.CLOSED; - resetCounts(); - log.info("成功次数已达到阈值,熔断器切换至关闭状态"); - } - } else { - resetCounts(); - log.info("熔断器处于关闭状态,重置计数器"); - } - } - - //记录失败 - public synchronized void recordFailure() { - failureCount.incrementAndGet(); - log.error("记录失败,当前失败次数:{}", failureCount); - lastFailureTime = System.currentTimeMillis(); - - if (state == CircuitBreakerState.HALF_OPEN) { - state = CircuitBreakerState.OPEN; - lastFailureTime = System.currentTimeMillis(); - log.warn("半开启状态下发生失败,熔断器切换至开启状态"); - } else if (failureCount.get() >= failureThreshold) { - state = CircuitBreakerState.OPEN; - log.error("失败次数已超过阈值,熔断器切换至开启状态"); - } - } - - //重置次数 - private void resetCounts() { - failureCount.set(0); - successCount.set(0); - requestCount.set(0); - } - - public CircuitBreakerState getState() { - return state; - } -} - -enum CircuitBreakerState { - //关闭,开启,半开启 - CLOSED, OPEN, HALF_OPEN -} diff --git a/version5/krpc-core/src/main/java/com/kama/client/circuitbreaker/CircuitBreakerProvider.java b/version5/krpc-core/src/main/java/com/kama/client/circuitbreaker/CircuitBreakerProvider.java deleted file mode 100644 index f94bf5c..0000000 --- a/version5/krpc-core/src/main/java/com/kama/client/circuitbreaker/CircuitBreakerProvider.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.kama.client.circuitbreaker; - -import lombok.extern.slf4j.Slf4j; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * @ClassName CircuitBreakerState - * @Description 提供熔断器 - * @Author Tong - * @LastChangeDate 2024-12-02 10:47 - * @Version v5.0 - */ -@Slf4j -public class CircuitBreakerProvider { - // 使用线程安全的 ConcurrentHashMap - private Map circuitBreakerMap = new ConcurrentHashMap<>(); - - public synchronized CircuitBreaker getCircuitBreaker(String serviceName) { - // 使用 computeIfAbsent,避免手动同步 - return circuitBreakerMap.computeIfAbsent(serviceName, key -> { - log.info("服务 [{}] 不存在熔断器,创建新的熔断器实例", serviceName); - // 创建并返回新熔断器 - return new CircuitBreaker(1, 0.5, 10000); - }); - } -} diff --git a/version5/krpc-core/src/main/java/com/kama/client/netty/NettyClientHandler.java b/version5/krpc-core/src/main/java/com/kama/client/netty/NettyClientHandler.java deleted file mode 100644 index 15c98ff..0000000 --- a/version5/krpc-core/src/main/java/com/kama/client/netty/NettyClientHandler.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.kama.client.netty; - -import common.message.RpcResponse; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.SimpleChannelInboundHandler; -import io.netty.util.AttributeKey; -import lombok.extern.slf4j.Slf4j; - -/** - * @ClassName NettyClientHandler - * @Description 客户端处理器 - * @Author Tong - * @LastChangeDate 2024-12-02 10:15 - * @Version v5.0 - */ -@Slf4j -public class NettyClientHandler extends SimpleChannelInboundHandler { - - - @Override - protected void channelRead0(ChannelHandlerContext ctx, RpcResponse response) throws Exception { - // 接收到response, 给channel设计别名,让sendRequest里读取response - AttributeKey RESPONSE_KEY = AttributeKey.valueOf("RPCResponse"); - // 将响应存入 Channel 属性 - ctx.channel().attr(RESPONSE_KEY).set(response); - ctx.channel().close(); - } - - @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { - log.error("Channel exception occurred", cause); - ctx.close(); - } -} diff --git a/version5/krpc-core/src/main/java/com/kama/client/netty/NettyClientInitializer.java b/version5/krpc-core/src/main/java/com/kama/client/netty/NettyClientInitializer.java deleted file mode 100644 index 3836d7e..0000000 --- a/version5/krpc-core/src/main/java/com/kama/client/netty/NettyClientInitializer.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.kama.client.netty; - - -import common.serializer.mycoder.MyDecoder; -import common.serializer.mycoder.MyEncoder; -import common.serializer.myserializer.Serializer; -import io.netty.channel.ChannelInitializer; -import io.netty.channel.ChannelPipeline; -import io.netty.channel.socket.SocketChannel; -import lombok.extern.slf4j.Slf4j; - -/** - * @ClassName NettyClientInitializer - * @Description 配置自定义的编码器以及Handler - * @Author Tong - * @LastChangeDate 2024-12-02 10:16 - * @Version v5.0 - */ -@Slf4j -public class NettyClientInitializer extends ChannelInitializer { - - - @Override - protected void initChannel(SocketChannel ch) throws Exception { - ChannelPipeline pipeline = ch.pipeline(); - - // 使用自定义的编码器和解码器 - try { - // 根据传入的序列化器类型初始化编码器 - pipeline.addLast(new MyEncoder(Serializer.getSerializerByCode(3))); - pipeline.addLast(new MyDecoder()); - pipeline.addLast(new NettyClientHandler()); - - log.info("Netty client pipeline initialized with serializer type: {}",Serializer.getSerializerByCode(3).toString()); - } catch (Exception e) { - log.error("Error initializing Netty client pipeline", e); - throw e; // 重新抛出异常,确保管道初始化失败时处理正确 - } - } -} diff --git a/version5/krpc-core/src/main/java/com/kama/client/proxy/ClientProxy.java b/version5/krpc-core/src/main/java/com/kama/client/proxy/ClientProxy.java deleted file mode 100644 index ef3f6e8..0000000 --- a/version5/krpc-core/src/main/java/com/kama/client/proxy/ClientProxy.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.kama.client.proxy; - -import com.kama.client.circuitbreaker.CircuitBreaker; -import com.kama.client.circuitbreaker.CircuitBreakerProvider; -import com.kama.client.retry.GuavaRetry; -import com.kama.client.rpcclient.RpcClient; -import com.kama.client.rpcclient.impl.NettyRpcClient; -import com.kama.client.servicecenter.ServiceCenter; -import com.kama.client.servicecenter.ZKServiceCenter; - - -import common.message.RpcRequest; -import common.message.RpcResponse; -import lombok.extern.slf4j.Slf4j; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; - -/** - * @ClassName ClientProxy - * @Description 动态代理 - * @Author Tong - * @LastChangeDate 2024-12-02 10:14 - * @Version v5.0 - */ -@Slf4j -public class ClientProxy implements InvocationHandler { - //传入参数service接口的class对象,反射封装成一个request - - private RpcClient rpcClient; - private ServiceCenter serviceCenter; - private CircuitBreakerProvider circuitBreakerProvider; - - public ClientProxy() throws InterruptedException { - serviceCenter = new ZKServiceCenter(); - rpcClient = new NettyRpcClient(serviceCenter); - circuitBreakerProvider = new CircuitBreakerProvider(); - } - - //jdk动态代理,每一次代理对象调用方法,都会经过此方法增强(反射获取request对象,socket发送到服务端) - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - //构建request - RpcRequest request = RpcRequest.builder() - .interfaceName(method.getDeclaringClass().getName()) - .methodName(method.getName()) - .params(args).paramsType(method.getParameterTypes()).build(); - //获取熔断器 - CircuitBreaker circuitBreaker = circuitBreakerProvider.getCircuitBreaker(method.getName()); - //判断熔断器是否允许请求经过 - if (!circuitBreaker.allowRequest()) { - log.warn("熔断器开启,请求被拒绝: {}", request); - //这里可以针对熔断做特殊处理,返回特殊值 - return null; - } - //数据传输 - RpcResponse response; - //后续添加逻辑:为保持幂等性,只对白名单上的服务进行重试 - // 如果启用重试机制,先检查是否需要重试 - if (serviceCenter.checkRetry(request.getInterfaceName())) { - //调用retry框架进行重试操作 - try { - log.info("尝试重试调用服务: {}", request.getInterfaceName()); - response = new GuavaRetry().sendServiceWithRetry(request, rpcClient); - } catch (Exception e) { - log.error("重试调用失败: {}", request.getInterfaceName(), e); - circuitBreaker.recordFailure(); - throw e; // 将异常抛给调用者 - } - } else { - //只调用一次 - response = rpcClient.sendRequest(request); - } - //记录response的状态,上报给熔断器 - if (response != null) { - if (response.getCode() == 200) { - circuitBreaker.recordSuccess(); - } else if (response.getCode() == 500) { - circuitBreaker.recordFailure(); - } - log.info("收到响应: {} 状态码: {}", request.getInterfaceName(), response.getCode()); - } - - return response != null ? response.getData() : null; - } - - public T getProxy(Class clazz) { - Object o = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, this); - return (T) o; - } -} diff --git a/version5/krpc-core/src/main/java/com/kama/client/retry/GuavaRetry.java b/version5/krpc-core/src/main/java/com/kama/client/retry/GuavaRetry.java deleted file mode 100644 index 0d1dde1..0000000 --- a/version5/krpc-core/src/main/java/com/kama/client/retry/GuavaRetry.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.kama.client.retry; - -import com.kama.client.rpcclient.RpcClient; -import com.github.rholder.retry.*; - -import common.message.RpcRequest; -import common.message.RpcResponse; -import lombok.extern.slf4j.Slf4j; - - -import java.util.Objects; -import java.util.concurrent.TimeUnit; - -/** - * @ClassName guavaRetry - * @Description 重试策略 - * @Author Tong - * @LastChangeDate 2024-12-02 10:44 - * @Version v5.0 - */ -@Slf4j -public class GuavaRetry { - - public RpcResponse sendServiceWithRetry(RpcRequest request, RpcClient rpcClient) { - Retryer retryer = RetryerBuilder.newBuilder() - //无论出现什么异常,都进行重试 - .retryIfException() - //返回结果为 error时进行重试 - .retryIfResult(response -> Objects.equals(response.getCode(), 500)) - //重试等待策略:等待 2s 后再进行重试 - .withWaitStrategy(WaitStrategies.fixedWait(2, TimeUnit.SECONDS)) - //重试停止策略:重试达到 3 次 - .withStopStrategy(StopStrategies.stopAfterAttempt(3)) - .withRetryListener(new RetryListener() { - @Override - public void onRetry(Attempt attempt) { - log.info("重试第 {} 次", attempt.getAttemptNumber()); - } - }) - .build(); - try { - return retryer.call(() -> rpcClient.sendRequest(request)); - } catch (Exception e) { - log.error("重试失败: 请求 {} 执行时遇到异常", request.getMethodName(), e); - } - return RpcResponse.fail("重试失败,所有重试尝试已结束"); - } -} diff --git a/version5/krpc-core/src/main/java/com/kama/client/rpcclient/RpcClient.java b/version5/krpc-core/src/main/java/com/kama/client/rpcclient/RpcClient.java deleted file mode 100644 index 80a4255..0000000 --- a/version5/krpc-core/src/main/java/com/kama/client/rpcclient/RpcClient.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.kama.client.rpcclient; - - -import common.message.RpcRequest; -import common.message.RpcResponse; - -/** - * @InterfaceName RpcClient - * @Description 定义底层通信方法 - * @Author Tong - * @LastChangeDate 2024-12-02 10:11 - * @Version v5.0 - */ - -public interface RpcClient { - RpcResponse sendRequest(RpcRequest request); -} diff --git a/version5/krpc-core/src/main/java/com/kama/client/rpcclient/impl/NettyRpcClient.java b/version5/krpc-core/src/main/java/com/kama/client/rpcclient/impl/NettyRpcClient.java deleted file mode 100644 index 7bd2e75..0000000 --- a/version5/krpc-core/src/main/java/com/kama/client/rpcclient/impl/NettyRpcClient.java +++ /dev/null @@ -1,103 +0,0 @@ -package com.kama.client.rpcclient.impl; - -import com.kama.client.netty.NettyClientInitializer; -import com.kama.client.rpcclient.RpcClient; -import com.kama.client.servicecenter.ServiceCenter; - -import common.message.RpcRequest; -import common.message.RpcResponse; -import io.netty.bootstrap.Bootstrap; -import io.netty.channel.Channel; -import io.netty.channel.ChannelFuture; -import io.netty.channel.EventLoopGroup; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.nio.NioSocketChannel; -import io.netty.util.AttributeKey; -import lombok.extern.slf4j.Slf4j; - - -import java.net.InetSocketAddress; - -/** - * @ClassName NettyRpcClient - * @Description Netty客户端 - * @Author Tong - * @LastChangeDate 2024-12-02 11:03 - * @Version v5.0 - */ -@Slf4j -public class NettyRpcClient implements RpcClient { - - private static final Bootstrap bootstrap; - private static final EventLoopGroup eventLoopGroup; - - private ServiceCenter serviceCenter; - - public NettyRpcClient(ServiceCenter serviceCenter) throws InterruptedException { - this.serviceCenter = serviceCenter; - } - - //netty客户端初始化 - static { - eventLoopGroup = new NioEventLoopGroup(); - bootstrap = new Bootstrap(); - bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class) - .handler(new NettyClientInitializer()); - } - - @Override - public RpcResponse sendRequest(RpcRequest request) { - //从注册中心获取host,post - InetSocketAddress address = serviceCenter.serviceDiscovery(request.getInterfaceName()); - if (address == null) { - log.error("服务发现失败,返回的地址为 null"); - return RpcResponse.fail("服务发现失败,地址为 null"); - } - String host = address.getHostName(); - int port = address.getPort(); - try { - // 连接到远程服务 - ChannelFuture channelFuture = bootstrap.connect(host, port).sync(); - Channel channel = channelFuture.channel(); - // 发送数据 - channel.writeAndFlush(request); - //sync()堵塞获取结果 - channel.closeFuture().sync(); - // 阻塞的获得结果,通过给channel设计别名,获取特定名字下的channel中的内容(这个在hanlder中设置) - // AttributeKey是,线程隔离的,不会由线程安全问题。 - // 当前场景下选择堵塞获取结果 - // 其它场景也可以选择添加监听器的方式来异步获取结果 channelFuture.addListener... - AttributeKey key = AttributeKey.valueOf("RPCResponse"); - RpcResponse response = channel.attr(key).get(); - - if (response == null) { - log.error("服务响应为空,可能是请求失败或超时"); - return RpcResponse.fail("服务响应为空"); - } - - log.info("收到响应: {}", response); - return response; - } catch (InterruptedException e) { - log.error("请求被中断,发送请求失败: {}", e.getMessage(), e); - Thread.currentThread().interrupt(); - } catch (Exception e) { - log.error("发送请求时发生异常: {}", e.getMessage(), e); - } finally { - // 连接断开后,优雅地关闭 Netty 资源 - shutdown(); - } - return RpcResponse.fail("请求失败"); - } - - // 优雅关闭 Netty 资源 - private void shutdown() { - try { - if (eventLoopGroup != null) { - eventLoopGroup.shutdownGracefully().sync(); - } - } catch (InterruptedException e) { - log.error("关闭 Netty 资源时发生异常: {}", e.getMessage(), e); - Thread.currentThread().interrupt(); - } - } -} diff --git a/version5/krpc-core/src/main/java/com/kama/client/rpcclient/impl/SimpleSocketRpcClient.java b/version5/krpc-core/src/main/java/com/kama/client/rpcclient/impl/SimpleSocketRpcClient.java deleted file mode 100644 index 589cc98..0000000 --- a/version5/krpc-core/src/main/java/com/kama/client/rpcclient/impl/SimpleSocketRpcClient.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.kama.client.rpcclient.impl; - -import com.kama.client.rpcclient.RpcClient; -import common.message.RpcRequest; -import common.message.RpcResponse; - - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.net.Socket; -import java.net.UnknownHostException; - -/** - * @ClassName SimpleSocketRpcClient - * @Description 实现简单客户都 - * @Author Tong - * @LastChangeDate 2024-12-02 10:12 - * @Version v5.0 - */ -public class SimpleSocketRpcClient implements RpcClient { - private String host; - private int port; - - public SimpleSocketRpcClient(String host, int port) { - this.host = host; - this.port = port; - } - - @Override - public RpcResponse sendRequest(RpcRequest request) { - // 定义响应对象 - RpcResponse response = null; - - // 创建 Socket 和流对象 - try (Socket socket = new Socket(host, port); - ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); - ObjectInputStream ois = new ObjectInputStream(socket.getInputStream())) { - - // 发送请求对象 - oos.writeObject(request); - oos.flush(); - - // 接收响应对象 - response = (RpcResponse) ois.readObject(); - - } catch (UnknownHostException e) { - System.err.println("未知的主机: " + host); - } catch (IOException e) { - System.err.println("I/O 错误: " + e.getMessage()); - } catch (ClassNotFoundException e) { - System.err.println("无法识别的类: " + e.getMessage()); - } - - return response; - } -} diff --git a/version5/krpc-core/src/main/java/com/kama/client/servicecenter/ServiceCenter.java b/version5/krpc-core/src/main/java/com/kama/client/servicecenter/ServiceCenter.java deleted file mode 100644 index f1aa801..0000000 --- a/version5/krpc-core/src/main/java/com/kama/client/servicecenter/ServiceCenter.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.kama.client.servicecenter; - - -import java.net.InetSocketAddress; - -/** - * @InterfaceName ServiceCenter - * @Description 服务中心接口 - * @Author Tong - * @LastChangeDate 2024-12-02 10:31 - * @Version v5.0 - */ - -public interface ServiceCenter { - // 查询:根据服务名查找地址 - InetSocketAddress serviceDiscovery(String serviceName); - - //判断是否可重试 - boolean checkRetry(String serviceName); -} diff --git a/version5/krpc-core/src/main/java/com/kama/client/servicecenter/ZKServiceCenter.java b/version5/krpc-core/src/main/java/com/kama/client/servicecenter/ZKServiceCenter.java deleted file mode 100644 index 93f2701..0000000 --- a/version5/krpc-core/src/main/java/com/kama/client/servicecenter/ZKServiceCenter.java +++ /dev/null @@ -1,113 +0,0 @@ -package com.kama.client.servicecenter; - -import com.kama.client.cache.ServiceCache; -import com.kama.client.servicecenter.ZKWatcher.watchZK; -import com.kama.client.servicecenter.balance.LoadBalance; -import com.kama.client.servicecenter.balance.impl.ConsistencyHashBalance; -import com.kama.client.servicecenter.balance.impl.RandomLoadBalance; -import lombok.extern.slf4j.Slf4j; -import org.apache.curator.RetryPolicy; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.retry.ExponentialBackoffRetry; - -import java.net.InetSocketAddress; -import java.util.List; -import java.util.Set; -import java.util.concurrent.CopyOnWriteArraySet; - -/** - * @ClassName ZKServiceCenter - * @Description 从服务中心获取服务地址 - * @Author Tong - * @LastChangeDate 2024-12-02 10:33 - * @Version v5.0 - */ -@Slf4j -public class ZKServiceCenter implements ServiceCenter { - // curator 提供的zookeeper客户端 - private CuratorFramework client; - //zookeeper根路径节点 - private static final String ROOT_PATH = "MyRPC"; - private static final String RETRY = "CanRetry"; - //serviceCache - private ServiceCache cache; - - private final LoadBalance loadBalance = new ConsistencyHashBalance(); - - //负责zookeeper客户端的初始化,并与zookeeper服务端进行连接 - public ZKServiceCenter() throws InterruptedException { - // 指数时间重试 - RetryPolicy policy = new ExponentialBackoffRetry(1000, 3); - // zookeeper的地址固定,不管是服务提供者还是,消费者都要与之建立连接 - // sessionTimeoutMs 与 zoo.cfg中的tickTime 有关系, - // zk还会根据minSessionTimeout与maxSessionTimeout两个参数重新调整最后的超时值。默认分别为tickTime 的2倍和20倍 - // 使用心跳监听状态 - this.client = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181") - .sessionTimeoutMs(40000).retryPolicy(policy).namespace(ROOT_PATH).build(); - this.client.start(); - log.info("Zookeeper 连接成功"); - //初始化本地缓存 - cache = new ServiceCache(); - //加入zookeeper事件监听器 - watchZK watcher = new watchZK(client, cache); - //监听启动 - watcher.watchToUpdate(ROOT_PATH); - } - - //根据服务名(接口名)返回地址 - @Override - public InetSocketAddress serviceDiscovery(String serviceName) { - try { - //先从本地缓存中找 - List addressList = cache.getServiceListFromCache(serviceName); - //如果找不到,再去zookeeper中找 - //这种i情况基本不会发生,或者说只会出现在初始化阶段 - if (addressList == null) { - addressList = client.getChildren().forPath("/" + serviceName); - // 如果本地缓存中没有该服务名的地址列表,则添加 - List cachedAddresses = cache.getServiceListFromCache(serviceName); - if (cachedAddresses == null || cachedAddresses.isEmpty()) { - // 假设 addServiceToCache 方法可以处理单个地址 - for (String address : addressList) { - cache.addServiceToCache(serviceName, address); - } - } - } - if (addressList.isEmpty()) { - log.warn("未找到服务:{}", serviceName); - return null; - } - // 负载均衡得到地址 - String address = loadBalance.balance(addressList); - return parseAddress(address); - } catch (Exception e) { - log.error("服务发现失败,服务名:{}", serviceName, e); - } - return null; - } - //保证线程安全使用CopyOnWriteArraySet - private Set retryServiceCache = new CopyOnWriteArraySet<>(); - //写一个白名单缓存,优化性能 - public boolean checkRetry(String serviceName) { - // 如果缓存为空,则从 Zookeeper 中加载白名单 - if (retryServiceCache.isEmpty()) { - try { - // 获取 Zookeeper 上的 /RETRY 路径下的所有子节点(服务名称) - List serviceList = client.getChildren().forPath("/" + RETRY); - // 将从 Zookeeper 获取到的服务名称列表添加到缓存中 - retryServiceCache.addAll(serviceList); - } catch (Exception e) { - log.error("检查重试失败,服务名:{}", serviceName, e); - } - } - // 判断服务是否在缓存的白名单中 - return retryServiceCache.contains(serviceName); - } - - // 字符串解析为地址 - private InetSocketAddress parseAddress(String address) { - String[] result = address.split(":"); - return new InetSocketAddress(result[0], Integer.parseInt(result[1])); - } -} diff --git a/version5/krpc-core/src/main/java/com/kama/client/servicecenter/ZKWatcher/watchZK.java b/version5/krpc-core/src/main/java/com/kama/client/servicecenter/ZKWatcher/watchZK.java deleted file mode 100644 index 396d4e8..0000000 --- a/version5/krpc-core/src/main/java/com/kama/client/servicecenter/ZKWatcher/watchZK.java +++ /dev/null @@ -1,98 +0,0 @@ -package com.kama.client.servicecenter.ZKWatcher; - -import com.kama.client.cache.ServiceCache; -import lombok.extern.slf4j.Slf4j; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.recipes.cache.ChildData; -import org.apache.curator.framework.recipes.cache.CuratorCache; -import org.apache.curator.framework.recipes.cache.CuratorCacheListener; - - -/** - * @ClassName watchZK - * @Description 节点监听 - * @Author Tong - * @LastChangeDate 2024-12-02 10:37 - * @Version v5.0 - */ -@Slf4j -public class watchZK { - // curator 提供的zookeeper客户端 - private CuratorFramework client; - //本地缓存 - ServiceCache cache; - - - public watchZK(CuratorFramework client, ServiceCache cache) { - this.client = client; - this.cache = cache; - } - - /** - * 监听当前节点和子节点的 更新,创建,删除 - * - * @param path - */ - public void watchToUpdate(String path) throws InterruptedException { - CuratorCache curatorCache = CuratorCache.build(client, "/"); - curatorCache.listenable().addListener(new CuratorCacheListener() { - @Override - public void event(Type type, ChildData childData, ChildData childData1) { - // 第一个参数:事件类型(枚举) - // 第二个参数:节点更新前的状态、数据 - // 第三个参数:节点更新后的状态、数据 - // 创建节点时:节点刚被创建,不存在 更新前节点 ,所以第二个参数为 null - // 删除节点时:节点被删除,不存在 更新后节点 ,所以第三个参数为 null - // 节点创建时没有赋予值 create /curator/app1 只创建节点,在这种情况下,更新前节点的 data 为 null,获取不到更新前节点的数据 - switch (type.name()) { - case "NODE_CREATED": // 监听器第一次执行时节点存在也会触发次事件 - String[] pathList = pasrePath(childData1); - if (pathList.length <= 2) break; - else { - String serviceName = pathList[1]; - String address = pathList[2]; - //将新注册的服务加入到本地缓存中 - cache.addServiceToCache(serviceName, address); - log.info("节点创建:服务名称 {} 地址 {}", serviceName, address); - } - break; - case "NODE_CHANGED": // 节点更新 - if (childData.getData() != null) { - log.debug("修改前的数据: {}", new String(childData.getData())); - } else { - log.debug("节点第一次赋值!"); - } - String[] oldPathList = pasrePath(childData); - String[] newPathList = pasrePath(childData1); - cache.replaceServiceAddress(oldPathList[1], oldPathList[2], newPathList[2]); - log.info("节点更新:服务名称 {} 地址从 {} 更新为 {}", oldPathList[1], oldPathList[2], newPathList[2]); - break; - case "NODE_DELETED": // 节点删除 - String[] pathList_d = pasrePath(childData); - if (pathList_d.length <= 2) break; - else { - String serviceName = pathList_d[1]; - String address = pathList_d[2]; - //将新注册的服务加入到本地缓存中 - cache.delete(serviceName, address); - log.info("节点删除:服务名称 {} 地址 {}", serviceName, address); - } - break; - default: - break; - } - } - }); - //开启监听 - curatorCache.start(); - } - - //解析节点对应地址 - public String[] pasrePath(ChildData childData) { - //获取更新的节点的路径 - String path = new String(childData.getPath()); - log.info("节点路径:{}",path); - //按照格式 ,读取 - return path.split("/"); - } -} diff --git a/version5/krpc-core/src/main/java/com/kama/client/servicecenter/balance/LoadBalance.java b/version5/krpc-core/src/main/java/com/kama/client/servicecenter/balance/LoadBalance.java deleted file mode 100644 index 1f1742c..0000000 --- a/version5/krpc-core/src/main/java/com/kama/client/servicecenter/balance/LoadBalance.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.kama.client.servicecenter.balance; - - -import java.util.List; - -/** - * @InterfaceName LoadBalance - * @Description 负载均衡接口 - * @Author Tong - * @LastChangeDate 2024-12-02 10:40 - * @Version v5.0 - */ - -public interface LoadBalance { - String balance(List addressList); - - void addNode(String node); - - void delNode(String node); -} diff --git a/version5/krpc-core/src/main/java/com/kama/client/servicecenter/balance/impl/ConsistencyHashBalance.java b/version5/krpc-core/src/main/java/com/kama/client/servicecenter/balance/impl/ConsistencyHashBalance.java deleted file mode 100644 index 119b9ea..0000000 --- a/version5/krpc-core/src/main/java/com/kama/client/servicecenter/balance/impl/ConsistencyHashBalance.java +++ /dev/null @@ -1,152 +0,0 @@ -package com.kama.client.servicecenter.balance.impl; - -import com.kama.client.servicecenter.balance.LoadBalance; -import lombok.extern.slf4j.Slf4j; - - -import java.util.*; -import java.util.concurrent.ConcurrentSkipListMap; -import java.util.concurrent.CopyOnWriteArrayList; - -/** - * @ClassName ConsistencyHashBalance - * @Description 一致性哈希算法负载均衡 - * @Author Tong - * @LastChangeDate 2024-12-02 10:42 - * @Version v5.0 - */ -@Slf4j -public class ConsistencyHashBalance implements LoadBalance { - - // 虚拟节点的个数 - private static final int VIRTUAL_NUM = 5; - - // 虚拟节点分配,key是hash值,value是虚拟节点服务器名称 - private SortedMap shards = new TreeMap(); - - // 真实节点列表 - private List realNodes = new LinkedList<>(); - - // 获取虚拟节点的个数 - public static int getVirtualNum() { - return VIRTUAL_NUM; - } - - // 初始化虚拟节点 - public void init(List serviceList) { - for (String server : serviceList) { - realNodes.add(server); - log.info("真实节点[{}] 被添加", server); - for (int i = 0; i < VIRTUAL_NUM; i++) { - String virtualNode = server + "&&VN" + i; - int hash = getHash(virtualNode); - shards.put(hash, virtualNode); - log.info("虚拟节点[{}] hash:{},被添加", virtualNode, hash); - } - } - } - - /** - * 获取被分配的节点名 - * - * @param node 请求的节点(通常是请求的唯一标识符) - * @return 负责该请求的真实节点名称 - */ - public String getServer(String node, List serviceList) { - if (shards.isEmpty()) { - init(serviceList); // 初始化,如果shards为空 - } - - int hash = getHash(node); - Integer key = null; - - SortedMap subMap = shards.tailMap(hash); - if (subMap.isEmpty()) { - key = shards.firstKey(); // 如果没有大于该hash的节点,则返回最小的hash值 - } else { - key = subMap.firstKey(); - } - - String virtualNode = shards.get(key); - return virtualNode.substring(0, virtualNode.indexOf("&&")); - } - - /** - * 添加节点 - * - * @param node 新加入的节点 - */ - public void addNode(String node) { - if (!realNodes.contains(node)) { - realNodes.add(node); - log.info("真实节点[{}] 上线添加", node); - for (int i = 0; i < VIRTUAL_NUM; i++) { - String virtualNode = node + "&&VN" + i; - int hash = getHash(virtualNode); - shards.put(hash, virtualNode); - log.info("虚拟节点[{}] hash:{},被添加", virtualNode, hash); - } - } - } - - /** - * 删除节点 - * - * @param node 被移除的节点 - */ - public void delNode(String node) { - if (realNodes.contains(node)) { - realNodes.remove(node); - log.info("真实节点[{}] 下线移除", node); - for (int i = 0; i < VIRTUAL_NUM; i++) { - String virtualNode = node + "&&VN" + i; - int hash = getHash(virtualNode); - shards.remove(hash); - log.info("虚拟节点[{}] hash:{},被移除", virtualNode, hash); - } - } - } - - /** - * FNV1_32_HASH算法 - */ - private static int getHash(String str) { - final int p = 16777619; - int hash = (int) 2166136261L; - for (int i = 0; i < str.length(); i++) - hash = (hash ^ str.charAt(i)) * p; - hash += hash << 13; - hash ^= hash >> 7; - hash += hash << 3; - hash ^= hash >> 17; - hash += hash << 5; - // 如果算出来的值为负数则取其绝对值 - if (hash < 0) - hash = Math.abs(hash); - return hash; - } - - @Override - public String balance(List addressList) { - // 如果 addressList 为空或 null,抛出 IllegalArgumentException - if (addressList == null || addressList.isEmpty()) { - throw new IllegalArgumentException("Address list cannot be null or empty"); - } - - // 使用UUID作为请求的唯一标识符来进行一致性哈希 - String random = UUID.randomUUID().toString(); - return getServer(random, addressList); - } - public SortedMap getShards() { - return shards; - } - - public List getRealNodes() { - return realNodes; - } - @Override - public String toString() { - return "ConsistencyHash"; - } -} - diff --git a/version5/krpc-core/src/main/java/com/kama/client/servicecenter/balance/impl/RandomLoadBalance.java b/version5/krpc-core/src/main/java/com/kama/client/servicecenter/balance/impl/RandomLoadBalance.java deleted file mode 100644 index 583030d..0000000 --- a/version5/krpc-core/src/main/java/com/kama/client/servicecenter/balance/impl/RandomLoadBalance.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.kama.client.servicecenter.balance.impl; - -import com.kama.client.servicecenter.balance.LoadBalance; -import lombok.extern.slf4j.Slf4j; - -import java.util.List; -import java.util.Random; -import java.util.concurrent.CopyOnWriteArrayList; - -/** - * @ClassName RandomLoadBalance - * @Description 随机法 - * @Author Tong - * @LastChangeDate 2024-12-02 10:40 - * @Version v5.0 - */ -@Slf4j -public class RandomLoadBalance implements LoadBalance { - // 将Random声明为类级别的字段 - private final Random random = new Random(); - - private final List addressList = new CopyOnWriteArrayList<>(); - - @Override - public String balance(List addressList) { - if (addressList == null || addressList.isEmpty()) { - throw new IllegalArgumentException("Address list cannot be null or empty"); - } - - int choose = random.nextInt(addressList.size()); - log.info("负载均衡选择了第 {} 号服务器,地址是:{}", choose, addressList.get(choose)); - return addressList.get(choose); // 返回选择的服务器地址 - } - - @Override - public void addNode(String node) { - // 如果是动态添加节点,可以将节点加入到addressList中 - addressList.add(node); - log.info("节点 {} 已加入负载均衡", node); - } - - @Override - public void delNode(String node) { - // 如果是动态删除节点,可以将节点从addressList中移除 - addressList.remove(node); - log.info("节点 {} 已从负载均衡中移除", node); - } -} diff --git a/version5/krpc-core/src/main/java/com/kama/client/servicecenter/balance/impl/RoundLoadBalance.java b/version5/krpc-core/src/main/java/com/kama/client/servicecenter/balance/impl/RoundLoadBalance.java deleted file mode 100644 index 15398a9..0000000 --- a/version5/krpc-core/src/main/java/com/kama/client/servicecenter/balance/impl/RoundLoadBalance.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.kama.client.servicecenter.balance.impl; - -import com.kama.client.servicecenter.balance.LoadBalance; -import lombok.extern.slf4j.Slf4j; - -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * @ClassName RoundLoadBalance - * @Description 轮询法 - * @Author Tong - * @LastChangeDate 2024-12-02 10:41 - * @Version v5.0 - */ -@Slf4j -public class RoundLoadBalance implements LoadBalance { - - // 使用 AtomicInteger 保证线程安全 - private AtomicInteger choose = new AtomicInteger(0); - - private List addressList = new CopyOnWriteArrayList<>(); - - @Override - public String balance(List addressList) { - if (addressList == null || addressList.isEmpty()) { - throw new IllegalArgumentException("Address list cannot be null or empty"); - } - - // 获取当前索引并更新为下一个 - int currentChoose = choose.getAndUpdate(i -> (i + 1) % addressList.size()); - - String selectedServer = addressList.get(currentChoose); - log.info("负载均衡选择了服务器: {}", selectedServer); - return selectedServer; // 返回被选择的服务器地址 - } - - @Override - public void addNode(String node) { - // 如果是动态添加节点,可以将节点加入到 addressList 中 - addressList.add(node); - log.info("节点 {} 已加入负载均衡", node); - } - - @Override - public void delNode(String node) { - // 如果是动态删除节点,可以将节点从 addressList 中移除 - addressList.remove(node); - log.info("节点 {} 已从负载均衡中移除", node); - } -} diff --git a/version5/krpc-core/src/main/java/com/kama/config/KRpcConfig.java b/version5/krpc-core/src/main/java/com/kama/config/KRpcConfig.java deleted file mode 100644 index 1c53401..0000000 --- a/version5/krpc-core/src/main/java/com/kama/config/KRpcConfig.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.kama.config; - -import com.kama.client.servicecenter.balance.impl.ConsistencyHashBalance; -import com.kama.server.serviceRegister.impl.ZKServiceRegister; -import common.serializer.myserializer.Serializer; -import lombok.*; - -/** - * @ClassName KRpcConfig - * @Description 配置文件 - * @Author Tong - * @LastChangeDate 2024-12-05 11:02 - * @Version v5.0 - */ -@AllArgsConstructor -@NoArgsConstructor -@Getter -@Setter -@Builder -@ToString -public class KRpcConfig { - //名称 - private String name = "krpc"; - //端口 - private Integer port = 9999; - //主机名 - private String host = "localhost"; - //版本号 - private String version = "1.0.0"; - //注册中心 - private String registry = new ZKServiceRegister().toString(); - //序列化器 - private String serializer = Serializer.getSerializerByCode(3).toString(); - //负载均衡 - private String loadBalance = new ConsistencyHashBalance().toString(); - -} diff --git a/version5/krpc-core/src/main/java/com/kama/config/RpcConstant.java b/version5/krpc-core/src/main/java/com/kama/config/RpcConstant.java deleted file mode 100644 index 6bda0b6..0000000 --- a/version5/krpc-core/src/main/java/com/kama/config/RpcConstant.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.kama.config; - - -/** - * @InterfaceName RpcConstants - * @Description - * @Author Tong - * @LastChangeDate 2024-12-05 11:17 - * @Version v5.0 - */ - -public interface RpcConstant { - - //默认的配置文件前缀 - String CONFIG_FILE_PREFIX = "rpc"; - - //默认的服务版本号 - String DEFAULT_VERSION_DEFAULT = "1.0.0"; - -} \ No newline at end of file diff --git a/version5/krpc-core/src/main/java/com/kama/server/netty/NettyRpcServerHandler.java b/version5/krpc-core/src/main/java/com/kama/server/netty/NettyRpcServerHandler.java deleted file mode 100644 index 0601b82..0000000 --- a/version5/krpc-core/src/main/java/com/kama/server/netty/NettyRpcServerHandler.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.kama.server.netty; - - -import common.message.RpcRequest; -import common.message.RpcResponse; -import io.netty.channel.ChannelFutureListener; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.SimpleChannelInboundHandler; -import lombok.AllArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import com.kama.server.provider.ServiceProvider; -import com.kama.server.ratelimit.RateLimit; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -/** - * @ClassName NettyRpcServerHandler - * @Description 服务端处理器 - * @Author Tong - * @LastChangeDate 2024-12-02 10:26 - * @Version v5.0 - */ -@AllArgsConstructor // 使用 Lombok 自动生成构造器 -@Slf4j -public class NettyRpcServerHandler extends SimpleChannelInboundHandler { - - private final ServiceProvider serviceProvider; // 确保通过构造器注入 ServiceProvider - - @Override - protected void channelRead0(ChannelHandlerContext ctx, RpcRequest request) throws Exception { - if (request == null) { - log.error("接收到非法请求,RpcRequest 为空"); - return; - } - RpcResponse response = getResponse(request); - ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); - } - - @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { - log.error("处理请求时发生异常: ", cause); - ctx.close(); - } - - private RpcResponse getResponse(RpcRequest rpcRequest) { - //得到服务名 - String interfaceName = rpcRequest.getInterfaceName(); - - //接口限流降级 - RateLimit rateLimit = serviceProvider.getRateLimitProvider().getRateLimit(interfaceName); - if (!rateLimit.getToken()) { - //如果获取令牌失败,进行限流降级,快速返回结果 - log.warn("服务限流,接口: {}", interfaceName); - return RpcResponse.fail("服务限流,接口 " + interfaceName + " 当前无法处理请求。请稍后再试。"); - } - - //得到服务端相应服务实现类 - Object service = serviceProvider.getService(interfaceName); - //反射调用方法 - Method method; - try { - method = service.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParamsType()); - Object invoke = method.invoke(service, rpcRequest.getParams()); - return RpcResponse.sussess(invoke); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - log.error("方法执行错误,接口: {}, 方法: {}", interfaceName, rpcRequest.getMethodName(), e); - return RpcResponse.fail("方法执行错误"); - } - } -} diff --git a/version5/krpc-core/src/main/java/com/kama/server/netty/NettyServerInitializer.java b/version5/krpc-core/src/main/java/com/kama/server/netty/NettyServerInitializer.java deleted file mode 100644 index 91c8f44..0000000 --- a/version5/krpc-core/src/main/java/com/kama/server/netty/NettyServerInitializer.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.kama.server.netty; - - -import common.serializer.mycoder.MyDecoder; -import common.serializer.mycoder.MyEncoder; -import common.serializer.myserializer.Serializer; -import io.netty.channel.ChannelInitializer; -import io.netty.channel.ChannelPipeline; -import io.netty.channel.socket.SocketChannel; -import lombok.AllArgsConstructor; -import com.kama.server.provider.ServiceProvider; - - -/** - * @ClassName NettyServerInitializer - * @Description 服务端初始化器 - * @Author Tong - * @LastChangeDate 2024-12-02 10:55 - * @Version v5.0 - */ -@AllArgsConstructor -public class NettyServerInitializer extends ChannelInitializer { - private ServiceProvider serviceProvider; - - @Override - protected void initChannel(SocketChannel ch) throws Exception { - ChannelPipeline pipeline = ch.pipeline(); - //使用自定义的编/解码器 - pipeline.addLast(new MyEncoder(Serializer.getSerializerByCode(3))); - pipeline.addLast(new MyDecoder()); - pipeline.addLast(new NettyRpcServerHandler(serviceProvider)); - } -} diff --git a/version5/krpc-core/src/main/java/com/kama/server/provider/ServiceProvider.java b/version5/krpc-core/src/main/java/com/kama/server/provider/ServiceProvider.java deleted file mode 100644 index 4bbde28..0000000 --- a/version5/krpc-core/src/main/java/com/kama/server/provider/ServiceProvider.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.kama.server.provider; - - -import com.kama.server.ratelimit.provider.RateLimitProvider; - -import com.kama.server.serviceRegister.ServiceRegister; -import com.kama.server.serviceRegister.impl.ZKServiceRegister; - - -import java.net.InetSocketAddress; -import java.util.HashMap; -import java.util.Map; - - -/** - * @ClassName ServiceProvider - * @Description 本地注册中心 - * @Author Tong - * @LastChangeDate 2024-12-02 10:21 - * @Version v5.0 - */ -public class ServiceProvider { - private Map interfaceProvider; - - private int port; - private String host; - //注册服务类 - private ServiceRegister serviceRegister; - //限流器 - private RateLimitProvider rateLimitProvider; - - public ServiceProvider(String host, int port) { - //需要传入服务端自身的网络地址 - this.host = host; - this.port = port; - this.interfaceProvider = new HashMap<>(); - this.serviceRegister = new ZKServiceRegister(); - this.rateLimitProvider = new RateLimitProvider(); - } - - public void provideServiceInterface(Object service, boolean canRetry) { - String serviceName = service.getClass().getName(); - Class[] interfaceName = service.getClass().getInterfaces(); - - for (Class clazz : interfaceName) { - //本机的映射表 - interfaceProvider.put(clazz.getName(), service); - //在注册中心注册服务 - serviceRegister.register(clazz.getName(), new InetSocketAddress(host, port), canRetry); - } - } - - public Object getService(String interfaceName) { - return interfaceProvider.get(interfaceName); - } - - public RateLimitProvider getRateLimitProvider() { - return rateLimitProvider; - } -} diff --git a/version5/krpc-core/src/main/java/com/kama/server/ratelimit/RateLimit.java b/version5/krpc-core/src/main/java/com/kama/server/ratelimit/RateLimit.java deleted file mode 100644 index 02a9998..0000000 --- a/version5/krpc-core/src/main/java/com/kama/server/ratelimit/RateLimit.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.kama.server.ratelimit; - - -/** - * @InterfaceName RateLimit - * @Description 限流接口 - * @Author Tong - * @LastChangeDate 2024-12-02 10:50 - * @Version v5.0 - */ - -public interface RateLimit { - //获取访问许可 - boolean getToken(); -} diff --git a/version5/krpc-core/src/main/java/com/kama/server/ratelimit/impl/TokenBucketRateLimitImpl.java b/version5/krpc-core/src/main/java/com/kama/server/ratelimit/impl/TokenBucketRateLimitImpl.java deleted file mode 100644 index df379d7..0000000 --- a/version5/krpc-core/src/main/java/com/kama/server/ratelimit/impl/TokenBucketRateLimitImpl.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.kama.server.ratelimit.impl; - -import com.kama.server.ratelimit.RateLimit; -import lombok.extern.slf4j.Slf4j; - - -/** - * @ClassName TokenBucketRateLimitImpl - * @Description 全局限流 - * @Author Tong - * @LastChangeDate 2024-12-02 10:53 - * @Version v5.0 - */ - -@Slf4j -public class TokenBucketRateLimitImpl implements RateLimit { - - // 令牌产生速率(单位:ms) - private final int rate; - // 桶容量 - private final int capacity; - // 当前桶容量 - private volatile int curCapacity; - // 上次请求时间戳 - private volatile long lastTimestamp; - - public TokenBucketRateLimitImpl(int rate, int capacity) { - this.rate = rate; - this.capacity = capacity; - this.curCapacity = capacity; - this.lastTimestamp = System.currentTimeMillis(); - } - - @Override - public boolean getToken() { - // 优化:同步仅限于关键部分,减少锁竞争 - synchronized (this) { - // 如果当前桶还有剩余,就直接返回 - if (curCapacity > 0) { - curCapacity--; - return true; - } - - long currentTimestamp = System.currentTimeMillis(); - // 如果距离上一次请求的时间大于 RATE 的时间间隔 - if (currentTimestamp - lastTimestamp >= rate) { - // 计算这段时间内生成的令牌数量 - int generatedTokens = (int) ((currentTimestamp - lastTimestamp) / rate); - if (generatedTokens > 1) { - // 只添加剩余令牌,确保不会超过桶的容量 - curCapacity = Math.min(capacity, curCapacity + generatedTokens - 1); - } - // 更新时间戳 - lastTimestamp = currentTimestamp; - return true; - } - return false; // 如果无法获取令牌,返回 false - } - } -} diff --git a/version5/krpc-core/src/main/java/com/kama/server/ratelimit/provider/RateLimitProvider.java b/version5/krpc-core/src/main/java/com/kama/server/ratelimit/provider/RateLimitProvider.java deleted file mode 100644 index 9ba551c..0000000 --- a/version5/krpc-core/src/main/java/com/kama/server/ratelimit/provider/RateLimitProvider.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.kama.server.ratelimit.provider; - -import com.kama.server.ratelimit.RateLimit; -import com.kama.server.ratelimit.impl.TokenBucketRateLimitImpl; -import lombok.extern.slf4j.Slf4j; - - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * @ClassName RateLimitProvider - * @Description 提供限流器 - * @Author Tong - * @LastChangeDate 2024-12-02 10:54 - * @Version v5.0 - */ -@Slf4j -public class RateLimitProvider { - private final Map rateLimitMap = new ConcurrentHashMap<>(); - - // 默认的限流桶容量和令牌生成速率 - private static final int DEFAULT_CAPACITY = 100; - private static final int DEFAULT_RATE = 10; - - // 提供限流实例 - public RateLimit getRateLimit(String interfaceName) { - return rateLimitMap.computeIfAbsent(interfaceName, key -> { - RateLimit rateLimit = new TokenBucketRateLimitImpl(DEFAULT_CAPACITY, DEFAULT_RATE); - log.info("为接口 [{}] 创建了新的限流策略: {}", interfaceName, rateLimit); - return rateLimit; - }); - } -} diff --git a/version5/krpc-core/src/main/java/com/kama/server/server/RpcServer.java b/version5/krpc-core/src/main/java/com/kama/server/server/RpcServer.java deleted file mode 100644 index beb6bb0..0000000 --- a/version5/krpc-core/src/main/java/com/kama/server/server/RpcServer.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.kama.server.server; - - -/** - * @InterfaceName RpcServer - * @Description 服务端接口 - * @Author Tong - * @LastChangeDate 2024-12-02 10:21 - * @Version v1.0 - */ - -public interface RpcServer { - void start(int port); - - void stop(); -} diff --git a/version5/krpc-core/src/main/java/com/kama/server/server/impl/NettyRpcServer.java b/version5/krpc-core/src/main/java/com/kama/server/server/impl/NettyRpcServer.java deleted file mode 100644 index ebab364..0000000 --- a/version5/krpc-core/src/main/java/com/kama/server/server/impl/NettyRpcServer.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.kama.server.server.impl; - -import io.netty.bootstrap.ServerBootstrap; -import io.netty.channel.ChannelFuture; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.nio.NioServerSocketChannel; -import lombok.AllArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import com.kama.server.netty.NettyServerInitializer; -import com.kama.server.provider.ServiceProvider; -import com.kama.server.server.RpcServer; - -/** - * @ClassName NettyRpcServer - * @Description Netty服务端 - * @Author Tong - * @LastChangeDate 2024-12-02 10:25 - * @Version v5.0 - */ -@Slf4j -@AllArgsConstructor -public class NettyRpcServer implements RpcServer { - private final ServiceProvider serviceProvider; // 只需要 ServiceProvider - private ChannelFuture channelFuture; // ChannelFuture 在 start 方法内初始化 - public NettyRpcServer(ServiceProvider serviceProvider) { - this.serviceProvider = serviceProvider; - } - - @Override - public void start(int port) { - NioEventLoopGroup bossGroup = new NioEventLoopGroup(); - NioEventLoopGroup workGroup = new NioEventLoopGroup(); - log.info("Netty服务端启动了"); - - try { - ServerBootstrap serverBootstrap = new ServerBootstrap(); - serverBootstrap.group(bossGroup, workGroup) - .channel(NioServerSocketChannel.class) - .childHandler(new NettyServerInitializer(serviceProvider)); - - // 同步阻塞,绑定端口启动服务 - channelFuture = serverBootstrap.bind(port).sync(); - log.info("Netty服务端已绑定端口:{}", port); - - // 阻塞,等待服务关闭 - channelFuture.channel().closeFuture().sync(); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - log.error("Netty服务端启动中断:{}", e.getMessage(), e); - } finally { - shutdown(bossGroup, workGroup); // 集中管理线程组资源 - log.info("Netty服务端关闭了"); - } - } - - @Override - public void stop() { - if (channelFuture != null) { - try { - channelFuture.channel().close().sync(); - log.info("Netty服务端主通道已关闭"); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - log.error("关闭Netty服务端主通道时中断:{}", e.getMessage(), e); - } - } else { - log.warn("Netty服务端主通道尚未启动,无法关闭"); - } - } - - private void shutdown(NioEventLoopGroup bossGroup, NioEventLoopGroup workGroup) { - if (bossGroup != null) { - bossGroup.shutdownGracefully().syncUninterruptibly(); - } - if (workGroup != null) { - workGroup.shutdownGracefully().syncUninterruptibly(); - } - } -} diff --git a/version5/krpc-core/src/main/java/com/kama/server/server/impl/SimpleRpcServer.java b/version5/krpc-core/src/main/java/com/kama/server/server/impl/SimpleRpcServer.java deleted file mode 100644 index 792c4ec..0000000 --- a/version5/krpc-core/src/main/java/com/kama/server/server/impl/SimpleRpcServer.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.kama.server.server.impl; - -import lombok.AllArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import com.kama.server.provider.ServiceProvider; -import com.kama.server.server.RpcServer; -import com.kama.server.server.work.WorkThread; - -import java.io.IOException; -import java.net.ServerSocket; -import java.net.Socket; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * @ClassName SimpleRpcServer - * @Description 简单服务端 - * @Author Tong - * @LastChangeDate 2024-12-02 10:23 - * @Version v5.0 - */ -@AllArgsConstructor -@Slf4j -public class SimpleRpcServer implements RpcServer { - private ServiceProvider serviceProvider; - // 控制服务器运行状态 - private AtomicBoolean running = new AtomicBoolean(true); - private ServerSocket serverSocket; - - @Override - public void start(int port) { - try { - serverSocket = new ServerSocket(port); - log.info("服务器启动了,监听端口:{}", port); - while (running.get()) { - try { - Socket socket = serverSocket.accept(); - new Thread(new WorkThread(socket, serviceProvider)).start(); - } catch (IOException e) { - if (running.get()) { // 如果不是因为服务器被停止导致的异常 - log.error("接受连接时发生异常:{}", e.getMessage(), e); - } - } - } - } catch (IOException e) { - log.error("服务器启动失败:{}", e.getMessage(), e); - } finally { - stop(); - } - } - - @Override - public void stop() { - if (!running.get()) return; // 防止重复停止 - - running.set(false); - log.info("服务器正在关闭..."); - - // 关闭 ServerSocket - if (serverSocket != null && !serverSocket.isClosed()) { - try { - serverSocket.close(); - log.info("服务器已关闭"); - } catch (IOException e) { - log.error("关闭服务器时发生异常:{}", e.getMessage(), e); - } - } - } -} diff --git a/version5/krpc-core/src/main/java/com/kama/server/server/work/WorkThread.java b/version5/krpc-core/src/main/java/com/kama/server/server/work/WorkThread.java deleted file mode 100644 index 447a600..0000000 --- a/version5/krpc-core/src/main/java/com/kama/server/server/work/WorkThread.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.kama.server.server.work; - - -import common.message.RpcRequest; -import common.message.RpcResponse; -import lombok.AllArgsConstructor; -import com.kama.server.provider.ServiceProvider; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.Socket; - -/** - * @ClassName WorkThread - * @Description - * @Author Tong - * @LastChangeDate 2024-12-02 10:22 - * @Version v5.0 - */ -@AllArgsConstructor -public class WorkThread implements Runnable { - private Socket socket; - private ServiceProvider serviceProvide; - - @Override - public void run() { - try { - ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); - ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); - //读取客户端传过来的request - RpcRequest rpcRequest = (RpcRequest) ois.readObject(); - //反射调用服务方法获取返回值 - RpcResponse rpcResponse = getResponse(rpcRequest); - //向客户端写入response - oos.writeObject(rpcResponse); - oos.flush(); - } catch (IOException | ClassNotFoundException e) { - e.printStackTrace(); - } - } - - private RpcResponse getResponse(RpcRequest rpcRequest) { - //得到服务名 - String interfaceName = rpcRequest.getInterfaceName(); - //得到服务端相应服务实现类 - Object service = serviceProvide.getService(interfaceName); - //反射调用方法 - Method method; - try { - method = service.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParamsType()); - Object invoke = method.invoke(service, rpcRequest.getParams()); - return RpcResponse.sussess(invoke); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - e.printStackTrace(); - return RpcResponse.fail("方法执行错误"); - } - } -} diff --git a/version5/krpc-core/src/main/java/com/kama/server/serviceRegister/ServiceRegister.java b/version5/krpc-core/src/main/java/com/kama/server/serviceRegister/ServiceRegister.java deleted file mode 100644 index dd0398d..0000000 --- a/version5/krpc-core/src/main/java/com/kama/server/serviceRegister/ServiceRegister.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.kama.server.serviceRegister; - - -import java.net.InetSocketAddress; - -/** - * @InterfaceName ServiceRegister - * @Description 服务注册接口 - * @Author Tong - * @LastChangeDate 2024-12-02 10:27 - * @Version v5.0 - */ - -public interface ServiceRegister { - void register(String serviceName, InetSocketAddress serviceAddress, boolean canRetry); -} diff --git a/version5/krpc-core/src/main/java/com/kama/server/serviceRegister/impl/ZKServiceRegister.java b/version5/krpc-core/src/main/java/com/kama/server/serviceRegister/impl/ZKServiceRegister.java deleted file mode 100644 index ce952e6..0000000 --- a/version5/krpc-core/src/main/java/com/kama/server/serviceRegister/impl/ZKServiceRegister.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.kama.server.serviceRegister.impl; - -import lombok.extern.slf4j.Slf4j; -import org.apache.curator.RetryPolicy; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.retry.ExponentialBackoffRetry; -import org.apache.zookeeper.CreateMode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import com.kama.server.serviceRegister.ServiceRegister; - -import java.net.InetSocketAddress; - -/** - * @ClassName ZKServiceRegister - * @Description zk服务注册中心 - * @Author Tong - * @LastChangeDate 2024-12-02 10:28 - * @Version v5.0 - */ -@Slf4j -public class ZKServiceRegister implements ServiceRegister { - private CuratorFramework client; - private static final String ROOT_PATH = "MyRPC"; - private static final String RETRY = "CanRetry"; - - public ZKServiceRegister() { - RetryPolicy policy = new ExponentialBackoffRetry(1000, 3); - this.client = CuratorFrameworkFactory.builder() - .connectString("127.0.0.1:2181") - .sessionTimeoutMs(40000) - .retryPolicy(policy) - .namespace(ROOT_PATH) - .build(); - this.client.start(); - log.info("Zookeeper 连接成功"); - } - - @Override - public void register(String serviceName, InetSocketAddress serviceAddress, boolean canRetry) { - try { - if (client.checkExists().forPath("/" + serviceName) == null) { - client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/" + serviceName); - log.info("服务节点 {} 创建成功", "/" + serviceName); - } - - String path = "/" + serviceName + "/" + getServiceAddress(serviceAddress); - if (client.checkExists().forPath(path) == null) { - client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path); - log.info("服务地址 {} 注册成功", path); - } else { - log.info("服务地址 {} 已经存在,跳过注册", path); - } - - if (canRetry) { - path = "/" + RETRY + "/" + serviceName; - client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path); - log.info("重试标识 {} 注册成功", path); - } - } catch (Exception e) { - log.error("服务注册失败,服务名:{},错误信息:{}", serviceName, e.getMessage(), e); - } - } - - @Override - public String toString() { - return "zookeeper"; - } - - private String getServiceAddress(InetSocketAddress serverAddress) { - return serverAddress.getHostName() + ":" + serverAddress.getPort(); - } -} diff --git a/version5/krpc-core/src/main/java/com/kama/test/balance/ConsistencyHashBalanceTest.java b/version5/krpc-core/src/main/java/com/kama/test/balance/ConsistencyHashBalanceTest.java deleted file mode 100644 index fa94dc6..0000000 --- a/version5/krpc-core/src/main/java/com/kama/test/balance/ConsistencyHashBalanceTest.java +++ /dev/null @@ -1,100 +0,0 @@ -package com.kama.test.balance; - -import com.kama.client.servicecenter.balance.impl.ConsistencyHashBalance; -import org.junit.Before; -import org.junit.Test; - -import java.util.Arrays; -import java.util.List; - -import static org.junit.Assert.*; - -/** - * @ClassName ConsistencyHashBalanceTest - * @Description 一致性哈希测试类 - * @Author Tong - * @LastChangeDate 2024-12-05 15:39 - * @Version v5.0 - */ -public class ConsistencyHashBalanceTest { - - private ConsistencyHashBalance balance; - - @Before - public void setUp() { - balance = new ConsistencyHashBalance(); - } - - @Test - public void testInit() { - // 模拟真实节点 - List nodes = Arrays.asList("server1", "server2", "server3"); - balance.init(nodes); - - // 验证虚拟节点的初始化是否正确 - assertTrue("shards should not be empty", balance.getShards().size() > 0); - assertTrue("realNodes should contain all nodes", balance.getRealNodes().containsAll(nodes)); - } - - @Test - public void testGetServer() { - // 模拟真实节点 - List nodes = Arrays.asList("server1", "server2", "server3"); - balance.init(nodes); - - // 使用 UUID 作为请求的唯一标识符进行负载均衡 - String server = balance.getServer("request-1", nodes); - assertNotNull("Server should not be null", server); - assertTrue("Server should be one of the real nodes", nodes.contains(server)); - - // 确保多个请求的分配在不同节点上(可根据测试的多次运行结果观察) - String server2 = balance.getServer("request-2", nodes); - assertNotEquals("Server should be different from the previous request", server, server2); - } - - @Test - public void testAddNode() { - // 模拟真实节点 - List nodes = Arrays.asList("server1", "server2"); - balance.init(nodes); - - // 新加入一个节点 - balance.addNode("server3"); - - // 验证新节点是否被加入 - assertTrue("server3 should be added", balance.getRealNodes().contains("server3")); - assertTrue("shards should contain virtual nodes for server3", balance.getShards().size() > 0); - } - - @Test - public void testDelNode() { - // 模拟真实节点 - List nodes = Arrays.asList("server1", "server2"); - balance.init(nodes); - - // 删除一个节点 - balance.delNode("server1"); - - // 验证该节点是否被移除 - assertFalse("server1 should be removed", balance.getRealNodes().contains("server1")); - assertFalse("shards should not contain virtual nodes for server1", balance.getShards().values().stream().anyMatch(vn -> vn.startsWith("server1"))); - } - - @Test(expected = IllegalArgumentException.class) - public void testBalanceWithEmptyList() { - // 测试地址列表为空时,抛出 IllegalArgumentException - balance.balance(Arrays.asList()); - } - - @Test(expected = IllegalArgumentException.class) - public void testBalanceWithNullList() { - // 测试地址列表为 null 时,抛出 IllegalArgumentException - balance.balance(null); - } - - @Test - public void testGetVirtualNum() { - // 测试虚拟节点的数量 - assertEquals("Virtual nodes count should be 5", 5, ConsistencyHashBalance.getVirtualNum()); - } -} diff --git a/version5/krpc-core/src/main/java/com/kama/test/balance/RandomLoadBalanceTest.java b/version5/krpc-core/src/main/java/com/kama/test/balance/RandomLoadBalanceTest.java deleted file mode 100644 index 4f1aa33..0000000 --- a/version5/krpc-core/src/main/java/com/kama/test/balance/RandomLoadBalanceTest.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.kama.test.balance; - -import com.kama.client.servicecenter.balance.impl.RandomLoadBalance; -import org.junit.Before; -import org.junit.Test; - -import java.util.Arrays; -import java.util.List; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -/** - * @ClassName RandomLoadBalanceTest - * @Description 随机负载均衡器测试 - * @Author Tong - * @LastChangeDate 2024-12-05 15:43 - * @Version v5.0 - */ -public class RandomLoadBalanceTest { - - private RandomLoadBalance loadBalance; - - @Before - public void setUp() { - // 在每个测试前初始化负载均衡器 - loadBalance = new RandomLoadBalance(); - } - - @Test - public void testBalance_WithNonEmptyList() { - // 准备一个非空的地址列表 - List addressList = Arrays.asList("server1", "server2", "server3"); - - // 使用 balance 方法选择一个服务器 - String selectedServer = loadBalance.balance(addressList); - - // 确保选择的服务器在列表中 - assertTrue(addressList.contains(selectedServer)); - } - - @Test(expected = IllegalArgumentException.class) - public void testBalance_WithEmptyList() { - // 测试空的节点列表,应该抛出 IllegalArgumentException 异常 - loadBalance.balance(Arrays.asList()); - } - - @Test(expected = IllegalArgumentException.class) - public void testBalance_WithNullList() { - // 测试 null 的节点列表,应该抛出 IllegalArgumentException 异常 - loadBalance.balance(null); - } - - @Test - public void testAddNode() { - // 测试添加节点到负载均衡器 - loadBalance.addNode("server4"); - - // 确保新添加的节点在负载均衡器中 - List addressList = Arrays.asList("server1", "server2", "server3", "server4"); - String selectedServer = loadBalance.balance(addressList); - assertTrue(addressList.contains(selectedServer)); - } - - @Test - public void testDelNode() { - // 测试从负载均衡器中移除节点 - loadBalance.addNode("server4"); - loadBalance.delNode("server4"); - - // 确保删除后的节点不再在负载均衡器中 - List addressList = Arrays.asList("server1", "server2", "server3"); - String selectedServer = loadBalance.balance(addressList); - assertFalse(addressList.contains("server4")); - } -} diff --git a/version5/krpc-core/src/main/java/com/kama/test/balance/RoundLoadBalanceTest.java b/version5/krpc-core/src/main/java/com/kama/test/balance/RoundLoadBalanceTest.java deleted file mode 100644 index 796a60f..0000000 --- a/version5/krpc-core/src/main/java/com/kama/test/balance/RoundLoadBalanceTest.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.kama.test.balance; - -import com.kama.client.servicecenter.balance.impl.RoundLoadBalance; -import org.junit.Before; -import org.junit.Test; - -import java.util.Arrays; -import java.util.List; - -import static org.junit.Assert.*; - -/** - * @ClassName RoundLoadBalanceTest - * @Description 轮询测试类 - * @Author Tong - * @LastChangeDate 2024-12-05 15:46 - * @Version v5.0 - */ -public class RoundLoadBalanceTest { - - private RoundLoadBalance loadBalance; - - @Before - public void setUp() { - // 在每个测试前初始化负载均衡器 - loadBalance = new RoundLoadBalance(); - } - - @Test - public void testBalance_WithNonEmptyList() { - // 准备一个非空的地址列表 - List addressList = Arrays.asList("server1", "server2", "server3"); - - // 执行 balance 方法并获取返回的服务器 - String selectedServer = loadBalance.balance(addressList); - - // 确保选择的服务器在列表中 - assertTrue(addressList.contains(selectedServer)); - } - - @Test(expected = IllegalArgumentException.class) - public void testBalance_WithEmptyList() { - // 测试空的节点列表,应该抛出 IllegalArgumentException 异常 - loadBalance.balance(Arrays.asList()); - } - - @Test(expected = IllegalArgumentException.class) - public void testBalance_WithNullList() { - // 测试 null 的节点列表,应该抛出 IllegalArgumentException 异常 - loadBalance.balance(null); - } - - @Test - public void testAddNode() { - // 测试添加节点到负载均衡器 - loadBalance.addNode("server4"); - - // 确保新添加的节点在负载均衡器中 - List addressList = Arrays.asList("server1", "server2", "server3", "server4"); - String selectedServer = loadBalance.balance(addressList); - assertTrue(addressList.contains(selectedServer)); - } - - @Test - public void testDelNode() { - // 测试从负载均衡器中移除节点 - loadBalance.addNode("server4"); - loadBalance.delNode("server4"); - - // 确保删除后的节点不再在负载均衡器中 - List addressList = Arrays.asList("server1", "server2", "server3"); - String selectedServer = loadBalance.balance(addressList); - assertFalse(addressList.contains("server4")); - } - - @Test - public void testBalance_RoundRobin() { - // 测试负载均衡是否按轮询顺序选择服务器 - List addressList = Arrays.asList("server1", "server2", "server3"); - - // 轮询选择服务器 - String firstSelection = loadBalance.balance(addressList); - String secondSelection = loadBalance.balance(addressList); - String thirdSelection = loadBalance.balance(addressList); - String fourthSelection = loadBalance.balance(addressList); // Should loop back to first - - // 确保选择的服务器是轮询顺序的 - assertNotEquals(firstSelection, secondSelection); - assertNotEquals(secondSelection, thirdSelection); - assertNotEquals(thirdSelection, fourthSelection); - assertEquals(firstSelection, fourthSelection); // Should be back to the first - } -} diff --git a/version5/krpc-core/src/main/java/com/kama/test/serializer/HessianSerializerTest.java b/version5/krpc-core/src/main/java/com/kama/test/serializer/HessianSerializerTest.java deleted file mode 100644 index 46c2854..0000000 --- a/version5/krpc-core/src/main/java/com/kama/test/serializer/HessianSerializerTest.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.kama.test.serializer; - - -import common.exception.SerializeException; -import common.serializer.myserializer.HessianSerializer; -import org.junit.Test; - -/** - * @ClassName HessianSerializerTest - * @Description Hessian测试类 - * @Author Tong - * @LastChangeDate 2024-12-05 15:21 - * @Version v5.0 - */ -import org.junit.Test; -import static org.junit.Assert.*; - -public class HessianSerializerTest { - - private HessianSerializer serializer = new HessianSerializer(); - - @Test - public void testSerializeAndDeserialize() { - // 创建一个测试对象 - String original = "Hello, Hessian!"; - - // 序列化 - byte[] serialized = serializer.serialize(original); - assertNotNull("序列化结果不应为 null", serialized); - - // 反序列化 - Object deserialized = serializer.deserialize(serialized, 3); - assertNotNull("反序列化结果不应为 null", deserialized); - - // 校验反序列化的结果 - assertEquals("反序列化的对象应该与原对象相同", original, deserialized); - } - - @Test - public void testDeserializeWithInvalidData() { - byte[] invalidData = new byte[]{1, 2, 3}; // 假数据 - - // 测试无效数据反序列化 - try { - serializer.deserialize(invalidData, 3); - fail("反序列化时应抛出异常"); - } catch (SerializeException e) { - assertEquals("Deserialization failed", e.getMessage()); - } - } -} - diff --git a/version5/krpc-core/src/main/java/com/kama/test/serializer/KryoSerializerTest.java b/version5/krpc-core/src/main/java/com/kama/test/serializer/KryoSerializerTest.java deleted file mode 100644 index b8532ae..0000000 --- a/version5/krpc-core/src/main/java/com/kama/test/serializer/KryoSerializerTest.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.kama.test.serializer; - - -import com.kama.pojo.User; -import common.exception.SerializeException; -import common.serializer.myserializer.KryoSerializer; -import org.junit.Test; - -import static org.junit.Assert.*; - -/** - * @ClassName KryoSerializer - * @Description kryo测试类 - * @Author Tong - * @LastChangeDate 2024-12-05 15:31 - * @Version v5.0 - */ -public class KryoSerializerTest { - - private KryoSerializer serializer = new KryoSerializer(); - - @Test - public void testSerializeAndDeserialize() { - // 创建一个 User 对象 - User originalUser = User.builder() - .id(1) - .userName("TestUser") - .gender(true) - .build(); - - // 序列化 - byte[] serialized = serializer.serialize(originalUser); - assertNotNull("序列化结果不应为 null", serialized); - - // 反序列化 - Object deserialized = serializer.deserialize(serialized, 1); - assertNotNull("反序列化结果不应为 null", deserialized); - - // 校验反序列化的对象是否与原对象相同 - assertTrue("反序列化的对象应该是 User 类型", deserialized instanceof User); - User deserializedUser = (User) deserialized; - assertEquals("反序列化的 User 应该与原 User 相同", originalUser, deserializedUser); - } - - @Test - public void testSerializeNullObject() { - // 测试序列化 null 对象 - try { - serializer.serialize(null); - fail("序列化 null 对象时应抛出 IllegalArgumentException"); - } catch (IllegalArgumentException e) { - assertEquals("Cannot serialize null object", e.getMessage()); - } - } - - @Test - public void testDeserializeNullBytes() { - // 测试反序列化 null 或空字节数组 - try { - serializer.deserialize(null, 1); - fail("反序列化 null 字节数组时应抛出 IllegalArgumentException"); - } catch (IllegalArgumentException e) { - assertEquals("Cannot deserialize null or empty byte array", e.getMessage()); - } - } - - @Test - public void testDeserializeEmptyBytes() { - // 测试反序列化空字节数组 - try { - serializer.deserialize(new byte[0], 1); - fail("反序列化空字节数组时应抛出 IllegalArgumentException"); - } catch (IllegalArgumentException e) { - assertEquals("Cannot deserialize null or empty byte array", e.getMessage()); - } - } - - @Test - public void testDeserializeInvalidMessageType() { - // 测试反序列化未知的 messageType - byte[] serialized = serializer.serialize(new User(1, "TestUser", true)); - try { - serializer.deserialize(serialized, 99); // 使用无效的 messageType - fail("反序列化时应抛出 SerializeException"); - } catch (SerializeException e) { - assertEquals("Deserialization failed", e.getMessage()); - } - } -} \ No newline at end of file diff --git a/version5/krpc-core/src/main/java/com/kama/test/serializer/ProtostuffSerializerTest.java b/version5/krpc-core/src/main/java/com/kama/test/serializer/ProtostuffSerializerTest.java deleted file mode 100644 index ed9fce5..0000000 --- a/version5/krpc-core/src/main/java/com/kama/test/serializer/ProtostuffSerializerTest.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.kama.test.serializer; - - -import com.kama.pojo.User; -import common.exception.SerializeException; -import common.serializer.myserializer.ProtostuffSerializer; -import org.junit.Test; - -import static org.junit.Assert.*; - -/** - * @ClassName ProtostuffSerializerTest - * @Description protostuff 序列化测试 - * @Author Tong - * @LastChangeDate 2024-12-05 15:32 - * @Version v5.0 - */ -public class ProtostuffSerializerTest { - - private ProtostuffSerializer serializer = new ProtostuffSerializer(); - - @Test - public void testSerializeAndDeserialize() { - // 创建一个 User 对象 - User originalUser = User.builder() - .id(1) - .userName("TestUser") - .gender(true) - .build(); - - // 序列化 - byte[] serialized = serializer.serialize(originalUser); - assertNotNull("序列化结果不应为 null", serialized); - - // 反序列化 - Object deserialized = serializer.deserialize(serialized, 1); - assertNotNull("反序列化结果不应为 null", deserialized); - - // 校验反序列化的对象是否与原对象相同 - assertTrue("反序列化的对象应该是 User 类型", deserialized instanceof User); - User deserializedUser = (User) deserialized; - assertEquals("反序列化的 User 应该与原 User 相同", originalUser, deserializedUser); - } - - @Test - public void testSerializeNullObject() { - // 测试序列化 null 对象 - try { - serializer.serialize(null); - fail("序列化 null 对象时应抛出 IllegalArgumentException"); - } catch (IllegalArgumentException e) { - assertEquals("Cannot serialize null object", e.getMessage()); - } - } - - @Test - public void testDeserializeNullBytes() { - // 测试反序列化 null 字节数组 - try { - serializer.deserialize(null, 1); - fail("反序列化 null 字节数组时应抛出 IllegalArgumentException"); - } catch (IllegalArgumentException e) { - assertEquals("Cannot deserialize null or empty byte array", e.getMessage()); - } - } - - @Test - public void testDeserializeEmptyBytes() { - // 测试反序列化空字节数组 - try { - serializer.deserialize(new byte[0], 1); - fail("反序列化空字节数组时应抛出 IllegalArgumentException"); - } catch (IllegalArgumentException e) { - assertEquals("Cannot deserialize null or empty byte array", e.getMessage()); - } - } - - @Test - public void testDeserializeInvalidMessageType() { - // 测试反序列化未知的 messageType - byte[] serialized = serializer.serialize(new User(1, "TestUser", true)); - try { - serializer.deserialize(serialized, 99); // 使用无效的 messageType - fail("反序列化时应抛出 SerializeException"); - } catch (SerializeException e) { - assertEquals("Unknown message type: 99", e.getMessage()); - } - } -} \ No newline at end of file diff --git a/version5/krpc-core/src/main/resources/META-INF/serializer/com.kama.common.serializer.myserializer.Serializer b/version5/krpc-core/src/main/resources/META-INF/serializer/com.kama.common.serializer.myserializer.Serializer deleted file mode 100644 index 90c3187..0000000 --- a/version5/krpc-core/src/main/resources/META-INF/serializer/com.kama.common.serializer.myserializer.Serializer +++ /dev/null @@ -1,5 +0,0 @@ -Hessian=com.kama.common.serializer.myserializer.HessianSerializer -protobuf=com.kama.common.serializer.myserializer.ProtobufSerializer -json=com.kama.common.serializer.myserializer.JsonSerializer -kryo=com.kama.common.serializer.myserializer.KryoSerializer -jdk=com.kama.common.serializer.myserializer.ObjectSerializer diff --git a/version5/krpc-core/target/classes/META-INF/serializer/com.kama.common.serializer.myserializer.Serializer b/version5/krpc-core/target/classes/META-INF/serializer/com.kama.common.serializer.myserializer.Serializer deleted file mode 100644 index 90c3187..0000000 --- a/version5/krpc-core/target/classes/META-INF/serializer/com.kama.common.serializer.myserializer.Serializer +++ /dev/null @@ -1,5 +0,0 @@ -Hessian=com.kama.common.serializer.myserializer.HessianSerializer -protobuf=com.kama.common.serializer.myserializer.ProtobufSerializer -json=com.kama.common.serializer.myserializer.JsonSerializer -kryo=com.kama.common.serializer.myserializer.KryoSerializer -jdk=com.kama.common.serializer.myserializer.ObjectSerializer diff --git a/version5/krpc-core/target/classes/com/kama/KRpcApplication.class b/version5/krpc-core/target/classes/com/kama/KRpcApplication.class deleted file mode 100644 index 0ec83d5..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/KRpcApplication.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/client/cache/ServiceCache.class b/version5/krpc-core/target/classes/com/kama/client/cache/ServiceCache.class deleted file mode 100644 index 84cacfe..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/client/cache/ServiceCache.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/client/circuitbreaker/CircuitBreaker$1.class b/version5/krpc-core/target/classes/com/kama/client/circuitbreaker/CircuitBreaker$1.class deleted file mode 100644 index 9651ad6..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/client/circuitbreaker/CircuitBreaker$1.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/client/circuitbreaker/CircuitBreaker.class b/version5/krpc-core/target/classes/com/kama/client/circuitbreaker/CircuitBreaker.class deleted file mode 100644 index 6d1b74a..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/client/circuitbreaker/CircuitBreaker.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/client/circuitbreaker/CircuitBreakerProvider.class b/version5/krpc-core/target/classes/com/kama/client/circuitbreaker/CircuitBreakerProvider.class deleted file mode 100644 index 5d8b40f..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/client/circuitbreaker/CircuitBreakerProvider.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/client/circuitbreaker/CircuitBreakerState.class b/version5/krpc-core/target/classes/com/kama/client/circuitbreaker/CircuitBreakerState.class deleted file mode 100644 index 3458bfb..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/client/circuitbreaker/CircuitBreakerState.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/client/netty/NettyClientHandler.class b/version5/krpc-core/target/classes/com/kama/client/netty/NettyClientHandler.class deleted file mode 100644 index a6cecd4..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/client/netty/NettyClientHandler.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/client/netty/NettyClientInitializer.class b/version5/krpc-core/target/classes/com/kama/client/netty/NettyClientInitializer.class deleted file mode 100644 index d197ba7..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/client/netty/NettyClientInitializer.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/client/proxy/ClientProxy.class b/version5/krpc-core/target/classes/com/kama/client/proxy/ClientProxy.class deleted file mode 100644 index 680b45a..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/client/proxy/ClientProxy.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/client/retry/GuavaRetry$1.class b/version5/krpc-core/target/classes/com/kama/client/retry/GuavaRetry$1.class deleted file mode 100644 index 7b72bc5..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/client/retry/GuavaRetry$1.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/client/retry/GuavaRetry.class b/version5/krpc-core/target/classes/com/kama/client/retry/GuavaRetry.class deleted file mode 100644 index 9dc5d0b..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/client/retry/GuavaRetry.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/client/rpcclient/RpcClient.class b/version5/krpc-core/target/classes/com/kama/client/rpcclient/RpcClient.class deleted file mode 100644 index b6f7885..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/client/rpcclient/RpcClient.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/client/rpcclient/impl/NettyRpcClient.class b/version5/krpc-core/target/classes/com/kama/client/rpcclient/impl/NettyRpcClient.class deleted file mode 100644 index 9b54f65..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/client/rpcclient/impl/NettyRpcClient.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/client/rpcclient/impl/SimpleSocketRpcClient.class b/version5/krpc-core/target/classes/com/kama/client/rpcclient/impl/SimpleSocketRpcClient.class deleted file mode 100644 index 8413ea0..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/client/rpcclient/impl/SimpleSocketRpcClient.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/client/servicecenter/ServiceCenter.class b/version5/krpc-core/target/classes/com/kama/client/servicecenter/ServiceCenter.class deleted file mode 100644 index fec3499..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/client/servicecenter/ServiceCenter.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/client/servicecenter/ZKServiceCenter.class b/version5/krpc-core/target/classes/com/kama/client/servicecenter/ZKServiceCenter.class deleted file mode 100644 index b5c20e8..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/client/servicecenter/ZKServiceCenter.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/client/servicecenter/ZKWatcher/watchZK$1.class b/version5/krpc-core/target/classes/com/kama/client/servicecenter/ZKWatcher/watchZK$1.class deleted file mode 100644 index c4bad2e..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/client/servicecenter/ZKWatcher/watchZK$1.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/client/servicecenter/ZKWatcher/watchZK.class b/version5/krpc-core/target/classes/com/kama/client/servicecenter/ZKWatcher/watchZK.class deleted file mode 100644 index bea96c0..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/client/servicecenter/ZKWatcher/watchZK.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/client/servicecenter/balance/LoadBalance.class b/version5/krpc-core/target/classes/com/kama/client/servicecenter/balance/LoadBalance.class deleted file mode 100644 index 7da849a..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/client/servicecenter/balance/LoadBalance.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/client/servicecenter/balance/impl/ConsistencyHashBalance.class b/version5/krpc-core/target/classes/com/kama/client/servicecenter/balance/impl/ConsistencyHashBalance.class deleted file mode 100644 index 66b6169..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/client/servicecenter/balance/impl/ConsistencyHashBalance.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/client/servicecenter/balance/impl/RandomLoadBalance.class b/version5/krpc-core/target/classes/com/kama/client/servicecenter/balance/impl/RandomLoadBalance.class deleted file mode 100644 index 2372cca..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/client/servicecenter/balance/impl/RandomLoadBalance.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/client/servicecenter/balance/impl/RoundLoadBalance.class b/version5/krpc-core/target/classes/com/kama/client/servicecenter/balance/impl/RoundLoadBalance.class deleted file mode 100644 index a0c60f2..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/client/servicecenter/balance/impl/RoundLoadBalance.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/config/KRpcConfig$KRpcConfigBuilder.class b/version5/krpc-core/target/classes/com/kama/config/KRpcConfig$KRpcConfigBuilder.class deleted file mode 100644 index 444ef88..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/config/KRpcConfig$KRpcConfigBuilder.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/config/KRpcConfig.class b/version5/krpc-core/target/classes/com/kama/config/KRpcConfig.class deleted file mode 100644 index e7ad52a..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/config/KRpcConfig.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/config/RpcConstant.class b/version5/krpc-core/target/classes/com/kama/config/RpcConstant.class deleted file mode 100644 index d1e1b9b..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/config/RpcConstant.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/server/netty/NettyRpcServerHandler.class b/version5/krpc-core/target/classes/com/kama/server/netty/NettyRpcServerHandler.class deleted file mode 100644 index 071b9ea..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/server/netty/NettyRpcServerHandler.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/server/netty/NettyServerInitializer.class b/version5/krpc-core/target/classes/com/kama/server/netty/NettyServerInitializer.class deleted file mode 100644 index 829a868..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/server/netty/NettyServerInitializer.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/server/provider/ServiceProvider.class b/version5/krpc-core/target/classes/com/kama/server/provider/ServiceProvider.class deleted file mode 100644 index 306f2b3..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/server/provider/ServiceProvider.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/server/ratelimit/RateLimit.class b/version5/krpc-core/target/classes/com/kama/server/ratelimit/RateLimit.class deleted file mode 100644 index 0e6dd0b..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/server/ratelimit/RateLimit.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/server/ratelimit/impl/TokenBucketRateLimitImpl.class b/version5/krpc-core/target/classes/com/kama/server/ratelimit/impl/TokenBucketRateLimitImpl.class deleted file mode 100644 index 83a9360..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/server/ratelimit/impl/TokenBucketRateLimitImpl.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/server/ratelimit/provider/RateLimitProvider.class b/version5/krpc-core/target/classes/com/kama/server/ratelimit/provider/RateLimitProvider.class deleted file mode 100644 index d8bfe2c..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/server/ratelimit/provider/RateLimitProvider.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/server/server/RpcServer.class b/version5/krpc-core/target/classes/com/kama/server/server/RpcServer.class deleted file mode 100644 index 65d240d..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/server/server/RpcServer.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/server/server/impl/NettyRpcServer.class b/version5/krpc-core/target/classes/com/kama/server/server/impl/NettyRpcServer.class deleted file mode 100644 index 2172d9f..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/server/server/impl/NettyRpcServer.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/server/server/impl/SimpleRpcServer.class b/version5/krpc-core/target/classes/com/kama/server/server/impl/SimpleRpcServer.class deleted file mode 100644 index 7e77c6b..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/server/server/impl/SimpleRpcServer.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/server/server/work/WorkThread.class b/version5/krpc-core/target/classes/com/kama/server/server/work/WorkThread.class deleted file mode 100644 index de933d0..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/server/server/work/WorkThread.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/server/serviceRegister/ServiceRegister.class b/version5/krpc-core/target/classes/com/kama/server/serviceRegister/ServiceRegister.class deleted file mode 100644 index 64da462..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/server/serviceRegister/ServiceRegister.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/server/serviceRegister/impl/ZKServiceRegister.class b/version5/krpc-core/target/classes/com/kama/server/serviceRegister/impl/ZKServiceRegister.class deleted file mode 100644 index 18c339c..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/server/serviceRegister/impl/ZKServiceRegister.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/test/balance/ConsistencyHashBalanceTest.class b/version5/krpc-core/target/classes/com/kama/test/balance/ConsistencyHashBalanceTest.class deleted file mode 100644 index e75c2b6..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/test/balance/ConsistencyHashBalanceTest.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/test/balance/RandomLoadBalanceTest.class b/version5/krpc-core/target/classes/com/kama/test/balance/RandomLoadBalanceTest.class deleted file mode 100644 index 6fc428a..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/test/balance/RandomLoadBalanceTest.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/test/balance/RoundLoadBalanceTest.class b/version5/krpc-core/target/classes/com/kama/test/balance/RoundLoadBalanceTest.class deleted file mode 100644 index 4289be1..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/test/balance/RoundLoadBalanceTest.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/test/serializer/HessianSerializerTest.class b/version5/krpc-core/target/classes/com/kama/test/serializer/HessianSerializerTest.class deleted file mode 100644 index 2dc41e7..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/test/serializer/HessianSerializerTest.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/test/serializer/KryoSerializerTest.class b/version5/krpc-core/target/classes/com/kama/test/serializer/KryoSerializerTest.class deleted file mode 100644 index a50e04e..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/test/serializer/KryoSerializerTest.class and /dev/null differ diff --git a/version5/krpc-core/target/classes/com/kama/test/serializer/ProtostuffSerializerTest.class b/version5/krpc-core/target/classes/com/kama/test/serializer/ProtostuffSerializerTest.class deleted file mode 100644 index 23e7707..0000000 Binary files a/version5/krpc-core/target/classes/com/kama/test/serializer/ProtostuffSerializerTest.class and /dev/null differ diff --git a/version5/krpc-core/target/krpc-core-1.0-SNAPSHOT.jar b/version5/krpc-core/target/krpc-core-1.0-SNAPSHOT.jar deleted file mode 100644 index 57e4489..0000000 Binary files a/version5/krpc-core/target/krpc-core-1.0-SNAPSHOT.jar and /dev/null differ diff --git a/version5/krpc-core/target/maven-archiver/pom.properties b/version5/krpc-core/target/maven-archiver/pom.properties deleted file mode 100644 index aa35714..0000000 --- a/version5/krpc-core/target/maven-archiver/pom.properties +++ /dev/null @@ -1,5 +0,0 @@ -#Generated by Maven -#Thu Dec 05 15:18:59 CST 2024 -groupId=com.kama -artifactId=krpc-core -version=1.0-SNAPSHOT diff --git a/version5/krpc-core/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst b/version5/krpc-core/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst deleted file mode 100644 index 651c8de..0000000 --- a/version5/krpc-core/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst +++ /dev/null @@ -1,55 +0,0 @@ -com\kama\common\serializer\myserializer\HessianSerializer.class -com\kama\server\netty\NettyServerInitializer.class -com\kama\common\serializer\myserializer\ProtostuffSerializer.class -com\kama\server\server\impl\NettyRpcServer.class -com\kama\client\circuitbreaker\CircuitBreaker.class -com\kama\common\serializer\myserializer\Serializer.class -com\kama\server\ratelimit\RateLimit.class -com\kama\common\message\RpcRequest$RpcRequestBuilder.class -com\kama\client\circuitbreaker\CircuitBreaker$1.class -com\kama\client\servicecenter\ZKServiceCenter.class -com\kama\client\rpcclient\impl\SimpleSocketRpcClient.class -com\kama\server\serviceRegister\ServiceRegister.class -com\kama\client\retry\GuavaRetry$1.class -com\kama\RpcApplication.class -com\kama\common\serializer\mycoder\MyEncoder.class -com\kama\common\serializer\myserializer\JsonSerializer.class -com\kama\server\server\RpcServer.class -com\kama\server\server\work\WorkThread.class -com\kama\client\servicecenter\balance\impl\ConsistencyHashBalance.class -com\kama\client\netty\NettyClientHandler.class -com\kama\server\TestServer.class -com\kama\common\config\RpcConstant.class -com\kama\client\cache\ServiceCache.class -com\kama\server\provider\ServiceProvider.class -com\kama\common\message\RpcRequest.class -com\kama\server\ratelimit\impl\TokenBucketRateLimitImpl.class -com\kama\client\rpcclient\RpcClient.class -com\kama\common\serializer\mycoder\MyDecoder.class -com\kama\client\proxy\ClientProxy.class -com\kama\client\retry\GuavaRetry.class -com\kama\server\server\impl\SimpleRpcServer.class -com\kama\common\util\ConfigUtil.class -com\kama\server\ratelimit\provider\RateLimitProvider.class -com\kama\server\netty\NettyRpcServerHandler.class -com\kama\client\netty\NettyClientInitializer.class -com\kama\common\message\MessageType.class -com\kama\client\servicecenter\balance\impl\RandomLoadBalance.class -com\kama\client\servicecenter\ZKWatcher\watchZK$1.class -com\kama\client\servicecenter\balance\LoadBalance.class -com\kama\common\config\KRpcConfig.class -com\kama\common\serializer\myserializer\ObjectSerializer.class -com\kama\common\exception\SerializeException.class -com\kama\client\circuitbreaker\CircuitBreakerProvider.class -com\kama\common\message\RpcResponse$RpcResponseBuilder.class -com\kama\client\circuitbreaker\CircuitBreakerState.class -com\kama\server\serviceRegister\impl\ZKServiceRegister.class -com\kama\client\rpcclient\impl\NettyRpcClient.class -com\kama\common\spi\SpiLoader.class -com\kama\client\servicecenter\balance\impl\RoundLoadBalance.class -com\kama\client\servicecenter\ZKWatcher\watchZK.class -com\kama\common\config\KRpcConfig$KRpcConfigBuilder.class -com\kama\common\message\RpcResponse.class -com\kama\client\TestClient.class -com\kama\common\serializer\myserializer\KryoSerializer.class -com\kama\client\servicecenter\ServiceCenter.class diff --git a/version5/krpc-core/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst b/version5/krpc-core/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst deleted file mode 100644 index 7222e88..0000000 --- a/version5/krpc-core/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst +++ /dev/null @@ -1,54 +0,0 @@ -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\common\spi\SpiLoader.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\common\serializer\myserializer\ProtostuffSerializer.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\client\rpcclient\impl\SimpleSocketRpcClient.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\client\servicecenter\ZKServiceCenter.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\common\serializer\mycoder\MyEncoder.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\server\server\impl\SimpleRpcServer.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\test\balance\ConsistencyHashBalanceTest.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\server\netty\NettyRpcServerHandler.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\test\balance\RandomLoadBalanceTest.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\common\serializer\mycoder\MyDecoder.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\server\serviceRegister\ServiceRegister.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\client\netty\NettyClientInitializer.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\common\serializer\myserializer\Serializer.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\client\servicecenter\balance\impl\ConsistencyHashBalance.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\server\server\RpcServer.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\client\servicecenter\balance\impl\RoundLoadBalance.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\client\servicecenter\ZKWatcher\watchZK.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\common\message\RpcResponse.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\common\config\RpcConstant.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\RpcApplication.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\common\message\MessageType.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\client\TestClient.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\server\serviceRegister\impl\ZKServiceRegister.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\client\rpcclient\impl\NettyRpcClient.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\client\retry\GuavaRetry.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\server\server\work\WorkThread.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\common\config\KRpcConfig.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\client\circuitbreaker\CircuitBreaker.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\client\netty\NettyClientHandler.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\test\serializer\KryoSerializerTest.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\test\serializer\HessianSerializerTest.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\test\serializer\ProtostuffSerializerTest.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\client\servicecenter\balance\impl\RandomLoadBalance.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\common\serializer\myserializer\KryoSerializer.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\server\server\impl\NettyRpcServer.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\server\ratelimit\RateLimit.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\client\servicecenter\balance\LoadBalance.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\server\ratelimit\impl\TokenBucketRateLimitImpl.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\client\rpcclient\RpcClient.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\client\servicecenter\ServiceCenter.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\client\cache\ServiceCache.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\server\ratelimit\provider\RateLimitProvider.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\common\util\ConfigUtil.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\client\proxy\ClientProxy.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\common\serializer\myserializer\HessianSerializer.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\server\netty\NettyServerInitializer.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\server\TestServer.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\server\provider\ServiceProvider.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\common\serializer\myserializer\JsonSerializer.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\common\exception\SerializeException.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\common\message\RpcRequest.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\common\serializer\myserializer\ObjectSerializer.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\client\circuitbreaker\CircuitBreakerProvider.java -D:\java_stduy\version5\krpc-core\src\main\java\com\kama\test\balance\RoundLoadBalanceTest.java diff --git a/version5/krpc-provider/pom.xml b/version5/krpc-provider/pom.xml deleted file mode 100644 index db9168e..0000000 --- a/version5/krpc-provider/pom.xml +++ /dev/null @@ -1,52 +0,0 @@ - - - 4.0.0 - - com.kama - version5 - 1.0-SNAPSHOT - - - krpc-provider - - - 17 - 17 - UTF-8 - - - - com.kama - krpc-api - 1.0-SNAPSHOT - - - com.kama - krpc-core - 1.0-SNAPSHOT - - - com.kama - krpc-common - 1.0-SNAPSHOT - - - cn.hutool - hutool-all - 5.8.10 - - - org.springframework.boot - spring-boot-starter-web - RELEASE - compile - - - org.springframework.boot - spring-boot-starter - - - - \ No newline at end of file diff --git a/version5/krpc-provider/src/main/java/com/kama/provider/ProviderTest.java b/version5/krpc-provider/src/main/java/com/kama/provider/ProviderTest.java deleted file mode 100644 index f55742b..0000000 --- a/version5/krpc-provider/src/main/java/com/kama/provider/ProviderTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.kama.provider; - -import com.kama.KRpcApplication; -import com.kama.provider.impl.UserServiceImpl; -import com.kama.server.provider.ServiceProvider; -import com.kama.server.server.RpcServer; -import com.kama.server.server.impl.NettyRpcServer; -import com.kama.service.UserService; -import lombok.extern.slf4j.Slf4j; - -/** - * @ClassName ProviderExample - * @Description 测试服务端 - * @Author Tong - * @LastChangeDate 2024-12-05 0:34 - * @Version v5.0 - */ -@Slf4j -public class ProviderTest { - - public static void main(String[] args) throws InterruptedException { - KRpcApplication.initialize(); - // 创建 UserService 实例 - UserService userService = new UserServiceImpl(); - ServiceProvider serviceProvider = new ServiceProvider("127.0.0.1", 9999); - // 发布服务接口到 ServiceProvider - serviceProvider.provideServiceInterface(userService, true); // 可以设置是否支持重试 - - // 启动 RPC 服务器并监听端口 - RpcServer rpcServer = new NettyRpcServer(serviceProvider); - rpcServer.start(9999); // 启动 Netty RPC 服务,监听 9999 端口 - log.info("RPC 服务端启动,监听端口 9999"); - } - -} diff --git a/version5/krpc-provider/src/main/java/com/kama/provider/impl/UserServiceImpl.java b/version5/krpc-provider/src/main/java/com/kama/provider/impl/UserServiceImpl.java deleted file mode 100644 index 64246d3..0000000 --- a/version5/krpc-provider/src/main/java/com/kama/provider/impl/UserServiceImpl.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.kama.provider.impl; - -import com.kama.pojo.User; -import com.kama.service.UserService; -import lombok.extern.slf4j.Slf4j; - -import java.util.Random; -import java.util.UUID; - -/** - * @ClassName UserServiceImpl - * @Description 接口实现类 - * @Author Tong - * @LastChangeDate 2024-12-04 23:55 - * @Version v5.0 - */ -@Slf4j -public class UserServiceImpl implements UserService { - - @Override - public User getUserByUserId(Integer id) { - log.info("客户端查询了ID={}的用户", id); - // 模拟从数据库中取用户的行为 - Random random = new Random(); - User user = User.builder() - .userName(UUID.randomUUID().toString()) // 使用随机生成的用户名 - .id(id) - .gender(random.nextBoolean()) // 随机生成性别 - .build(); - log.info("返回用户信息: {}", user); - return user; - } - - @Override - public Integer insertUserId(User user) { - log.info("插入数据成功,用户名={}", user.getUserName()); - // 假设插入数据返回用户ID - return user.getId(); - } -} - diff --git a/version5/krpc-provider/src/main/resources/application.properties b/version5/krpc-provider/src/main/resources/application.properties deleted file mode 100644 index 9312248..0000000 --- a/version5/krpc-provider/src/main/resources/application.properties +++ /dev/null @@ -1,7 +0,0 @@ -rpc.name=krpc -rpc.version=1.0.0 -rpc.port=9999 -rpc.serializer=Hessian -rpc.host=localhost -rpc.registry=zookeeper -rpc.loadBalance=ConsistencyHash diff --git a/version5/krpc-provider/target/classes/META-INF/application.properties b/version5/krpc-provider/target/classes/META-INF/application.properties deleted file mode 100644 index e69de29..0000000 diff --git a/version5/krpc-provider/target/classes/application.properties b/version5/krpc-provider/target/classes/application.properties deleted file mode 100644 index 9312248..0000000 --- a/version5/krpc-provider/target/classes/application.properties +++ /dev/null @@ -1,7 +0,0 @@ -rpc.name=krpc -rpc.version=1.0.0 -rpc.port=9999 -rpc.serializer=Hessian -rpc.host=localhost -rpc.registry=zookeeper -rpc.loadBalance=ConsistencyHash diff --git a/version5/krpc-provider/target/classes/com/kama/provider/ProviderTest.class b/version5/krpc-provider/target/classes/com/kama/provider/ProviderTest.class deleted file mode 100644 index cd2eb0a..0000000 Binary files a/version5/krpc-provider/target/classes/com/kama/provider/ProviderTest.class and /dev/null differ diff --git a/version5/krpc-provider/target/classes/com/kama/provider/impl/UserServiceImpl.class b/version5/krpc-provider/target/classes/com/kama/provider/impl/UserServiceImpl.class deleted file mode 100644 index 1eb7904..0000000 Binary files a/version5/krpc-provider/target/classes/com/kama/provider/impl/UserServiceImpl.class and /dev/null differ diff --git a/version5/krpc-provider/target/krpc-provider-1.0-SNAPSHOT.jar b/version5/krpc-provider/target/krpc-provider-1.0-SNAPSHOT.jar deleted file mode 100644 index 95956ac..0000000 Binary files a/version5/krpc-provider/target/krpc-provider-1.0-SNAPSHOT.jar and /dev/null differ diff --git a/version5/krpc-provider/target/maven-archiver/pom.properties b/version5/krpc-provider/target/maven-archiver/pom.properties deleted file mode 100644 index d937b1d..0000000 --- a/version5/krpc-provider/target/maven-archiver/pom.properties +++ /dev/null @@ -1,5 +0,0 @@ -#Generated by Maven -#Thu Dec 05 20:00:58 CST 2024 -groupId=com.kama -artifactId=krpc-provider -version=1.0-SNAPSHOT diff --git a/version5/krpc-provider/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst b/version5/krpc-provider/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst deleted file mode 100644 index af204cc..0000000 --- a/version5/krpc-provider/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst +++ /dev/null @@ -1,3 +0,0 @@ -com\kama\provider\impl\UserServiceImpl.class -com\kama\provider\impl\ProviderTestConfig.class -com\kama\provider\ProviderExample.class diff --git a/version5/krpc-provider/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst b/version5/krpc-provider/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst deleted file mode 100644 index 7d48ad0..0000000 --- a/version5/krpc-provider/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst +++ /dev/null @@ -1,3 +0,0 @@ -D:\java_stduy\version5\krpc-provider\src\main\java\com\kama\provider\ProviderExample.java -D:\java_stduy\version5\krpc-provider\src\main\java\com\kama\provider\impl\ProviderTestConfig.java -D:\java_stduy\version5\krpc-provider\src\main\java\com\kama\provider\impl\UserServiceImpl.java diff --git a/version5/pom.xml b/version5/pom.xml deleted file mode 100644 index ed2a11b..0000000 --- a/version5/pom.xml +++ /dev/null @@ -1,97 +0,0 @@ - - - 4.0.0 - - com.kama - version5 - 1.0-SNAPSHOT - pom - - krpc-core - krpc-consumer - krpc-provider - krpc-api - krpc-common - - - - 17 - 17 - UTF-8 - - - - - org.projectlombok - lombok - 1.18.30 - compile - - - - - org.springframework.boot - spring-boot-starter - 3.3.5 - - - - - io.netty - netty-all - 4.1.51.Final - compile - - - com.alibaba - fastjson - 1.2.83 - - - com.esotericsoftware - kryo - 4.0.2 - - - com.caucho - hessian - 4.0.66 - - - io.protostuff - protostuff-core - 1.7.4 - - - io.protostuff - protostuff-runtime - 1.7.4 - - - com.github.rholder - guava-retrying - 2.0.0 - - - - - - org.springframework.boot - spring-boot-dependencies - 3.3.5 - import - pom - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - \ No newline at end of file