Apache shenyu 安装与使用

我爱海鲸 2025-09-18 10:56:34 暂无标签

简介网关、shen yu、api

官网:https://shenyu.apache.org/zh/

1、docker快速安装

docker pull apache/shenyu-admin
docker network create shenyu

docker run -d -p 9095:9095 -p 9090:9090 --net shenyu \
  -e "shenyu.httpPath =http://【你的虚拟机ip】:9095" \
  apache/shenyu-admin

docker pull apache/shenyu-bootstrap

   docker run -d \
  -p 9195:9195 \
  --name shenyu-bootstrap \
  --net shenyu \
  --env SHENYU_SYNC_WEBSOCKET_URLS=ws://【你的虚拟机ip】:9095/websocket \
  apache/shenyu-bootstrap

默认账号: admin

默认密码: 123456

2、简单入门

参考:https://www.cnblogs.com/qjwyss/p/16531825.html

jdk-17相关 github直接下载地址:https://github.com/apache/shenyu/releases/tag/v2.7.0

https://shenyu.apache.org/zh/download/   直接去官网下载 2.6.1 支持jdk-8

需要下载两个服务模块:admin和bootstrap

admin是用来进行后台管理的,bootstrap是真正的网关服务模块

admin相关的配置修改:

修改application.yml配置文件中的以下参数:
server:
  port: 19095
  address: 0.0.0.0
端口修改为19095,在windows下他原来的端口被占用了
spring:
  application:
    name: shenyu-admin
  profiles:
    active: mysql
active修改为mysql
shenyu:
  httpPath: localhost:19095
需要添加httpPath: 【你部署admin的ip】:19095
admin部署完之后你登录的时候会出现一直进不去登陆页面的情况,查看接口后会发现它调用了一个奇怪的ip【在docker容器内是容器的ip】

修改application-mysql.yml配置文件中的以下参数:
spring:
  datasource:
    url: jdbc:mysql://192.168.176.129:3306/shenyu?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=convertToNull
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
修改为你本地的数据库

还有一个问题在启动的时候会报mysql链接的错,需要在ext-lib目录中添加mysql链接的jar包才行,详情可以查看这个issue:https://github.com/apache/shenyu/issues/5959

mysql8.0的链接jar:https://repo1.maven.org/maven2/mysql/mysql-connector-java/8.0.18/mysql-connector-java-8.0.18.jar

数据库的初始化脚本:https://github.com/apache/shenyu/tree/v2.7.0/db    (jdk-17)

如果在调用的时候出现:Gateway address not found from registry.

可以看看nacos的分组是否不一致的问题

修改 Shenyu Admin 配置
在 Shenyu Admin 的 application.yml 中确保 Nacos 客户端使用相同的 group:

yaml
shenyu:
  register:
    nacos:
      group: YOUR_GROUP_NAME  # 与客户端保持一致
修改 Shenyu Bootstrap 配置
确保网关实例的 Nacos 配置也匹配:

yaml
shenyu:
  sync:
    nacos:
      group: YOUR_GROUP_NAME  # 与上述配置一致

你可以在shneyu网关的配置文件中进行配置,不然它会使用它默认的分组名:SHENYU_GROUP

shenyu网关接入nacos配置中心和注册中心-CSDN博客

admin配置如下:

# 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.

server:
  port: 19095
  address: 0.0.0.0

spring:
  profiles:
    active: mysql
  thymeleaf:
    cache: true
    encoding: utf-8
    enabled: true
    prefix: classpath:/static/
    suffix: .html
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher
  jackson:
    time-zone: GMT+8 # GMT , Asia/Shanghai
  messages:
    basename: message/i18n


management:
  health:
    mail:
      enabled: off
  endpoints:
    web:
      exposure:
        include:
          - 'health'
          - 'prometheus'
    enabled-by-default: true

mybatis:
  config-location: classpath:/mybatis/mybatis-config.xml
  mapper-locations: classpath:/mappers/*.xml
  type-handlers-package: org.apache.shenyu.admin.mybatis.handler

shenyu:
  httpPath: localhost:19095
  register:
    registerType: http
    serverLists:
    props:
      sessionTimeout: 5000
      connectionTimeout: 2000
      checked: true
      zombieCheckThreads: 10
      zombieCheckTimes: 5
      scheduledTime: 10
      nacosNameSpace: ShenyuRegisterCenter
  sync:
    websocket:
      enabled: true
      messageMaxSize: 10240
      allowOrigins: ws://localhost:19095;ws://localhost:9195;
#    apollo:
#      meta: http://localhost:8080
#      appId: shenyu
#      portalUrl: http://localhost:8070
#      env: dev
#      clusterName: test
#      namespace: application
#      token: 0fff5645fc74ee5e0d63a6389433c8c8afc0beea31eed0279ecc1c8961d12da9
#    zookeeper:
#      url: localhost:2181
#      sessionTimeout: 5000
#      connectionTimeout: 2000
#    http:
#      enabled: true
    nacos:
      url: 【nacos ip】:8848
      namespace: 【nacos命名空间】
      username: nacos
      password: nacos
      group: SHNEYU_GROUP
      # context-path: nacos
#      acm:
#        enabled: false
#        endpoint: acm.aliyun.com
#        namespace:
#        accessKey:
#        secretKey:
#    polaris:
#      url: 127.0.0.1:8093
#      namespace:
#      fileGroup:
#    etcd:
#      url: http://localhost:2379
#    consul:
#      url: http://localhost:8500
  ldap:
    enabled: false
    url: ldap://xxxx:xxx
    bind-dn: cn=xxx,dc=xxx,dc=xxx
    password: xxxx
    base-dn: ou=xxx,dc=xxx,dc=xxx
    object-class: person
    login-field: cn
  jwt:
    expired-seconds: 86400000
  shiro:
    white-list:
      - /
      - /favicon.*
      - /static/**
      - /index**
      - /platform/login
      - /websocket
      - /error
      - /actuator/health
      - /actuator/health/** # /actuator/health/readiness /actuator/health/liveness
      - /actuator/prometheus
      - /swagger-ui.html
      - /swagger-ui/**
      - /webjars/**
      - /v3/api-docs/**
      - /csrf
      - /alert/report
  dashboard:
    core:
      onlySuperAdminPermission:
        - system:manager:add
        - system:manager:edit
        - system:manager:delete
        - system:role:add
        - system:role:edit
        - system:role:delete
        - system:resource:addButton
        - system:resource:addMenu
        - system:resource:editButton
        - system:resource:editMenu
        - system:resource:deleteButton
        - system:resource:deleteMenu

springdoc:
  api-docs:
    enabled: true
  swagger-ui:
    enabled: true
    tags-sorter: alpha
  packages-to-scan: org.apache.shenyu.admin.controller
  paths-to-match: /**

logging:
  level:
    root: info
    org.springframework.boot: info
    org.apache.ibatis: info
    org.apache.shenyu.bonuspoint: info
    org.apache.shenyu.lottery: info
    org.apache.shenyu: info
#    org.apache.shenyu.admin.utils.HttpUtils: debug

bootstrap配置:

注册nacos的时候有一个比较重要的配置:

shenyu:
  # 元数据注册到 Nacos(关键!)
  register:
    enabled: true
    registerType: nacos
    serverLists: 【ip】:8848
    props:
      nacosNameSpace: 56563ec6-701b-465b-b5e9-ed6eb948d65f
      groupName: DEFAULT_GROUP
      name: shenyu-bootstrap-33

 

# 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.

server:
  port: 9195
  address: 0.0.0.0
  compression:
    enabled: true
    minResponseSize: 1MB # If the response data is greater than 1MB, enable compression.

spring:
  main:
    allow-bean-definition-overriding: true
  application:
    name: shenyu-bootstrap
  codec:
    max-in-memory-size: 2MB
  cloud:
    discovery:
      enabled: true
    nacos:
      discovery:
        server-addr: 【nacos ip】:8848 # Spring Cloud Alibaba Dubbo use this.
        enabled: true
        namespace: 【nacos命名空间】
        username: nacos
        password: nacos
        group: SHENYU_GROUP

# if you want use ribbon please config every server.
#springCloud-test:
#  ribbon:
#    NIWSServerListClassName: com.netflix.niws.loadbalancer.DiscoveryEnabledNIWSServerList

eureka:
  client:
    enabled: false
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
  instance:
    prefer-ip-address: true

#  security:
#    oauth2:
#      client:
#        registration:
#          <your client-registration-id>:
#            client-id: <your client-id>
#            client-secret: <your client-secret>
#        provider:
#          <your client-registration-id>:
#            authorization-uri: <your authorization-uri>
#            token-uri: <your access-token-uri>
#            user-info-uri: <your user-info-uri>
#            jwk-set-uri: <your jwk-set-uri>

management:
  health:
    redis:
      enabled: false
    elasticsearch:
      enabled: false
  endpoint:
    health:
      enabled: true
      show-details: always
  endpoints:
    web:
      exposure:
        include: "*" # or health,info


shenyu:
  httpPath: localhost:9195
  selectorMatchCache:
    ## selector L1 cache
    cache:
      enabled: false
      initialCapacity: 10000 # initial capacity in cache
      maximumSize: 10000 # max size in cache
    ## selector L2 cache, use trie as L2 cache
    trie:
      enabled: false
      cacheSize: 128 # the number of plug-ins
      matchMode: antPathMatch
  ruleMatchCache:
    ## rule L1 cache
    cache:
      enabled: true
      initialCapacity: 10000 # initial capacity in cache
      maximumSize: 65536 # max size in cache
    ## rule L2 cache, use trie as L2 cache
    trie:
      enabled: false
      cacheSize: 1024 # the number of selectors
      matchMode: antPathMatch
  netty:
    http:
      # set to false, user can custom the netty tcp server config.
      webServerFactoryEnabled: true
      selectCount: 1
      workerCount: 8
      accessLog: false
      serverSocketChannel:
        soRcvBuf: 87380
        soBackLog: 128
        soReuseAddr: false
        connectTimeoutMillis: 10000
        writeBufferHighWaterMark: 65536
        writeBufferLowWaterMark: 32768
        writeSpinCount: 16
        autoRead: false
        allocType: "unpooled"
        messageSizeEstimator: 8
        singleEventExecutorPerGroup: true
      socketChannel:
        soKeepAlive: false
        soReuseAddr: false
        soLinger: -1
        tcpNoDelay: true
        soRcvBuf: 87380
        soSndBuf: 16384
        ipTos: 0
        allowHalfClosure: false
        connectTimeoutMillis: 10000
        writeBufferHighWaterMark: 65536
        writeBufferLowWaterMark: 32768
        writeSpinCount: 16
        autoRead: false
        allocType: "unpooled"
        messageSizeEstimator: 8
        singleEventExecutorPerGroup: true
      sni:
        enabled: false
        mod: k8s #manul
        defaultK8sSecretNamespace: shenyu-ingress
        defaultK8sSecretName: default-cert
#        mod: manual
#        certificates:
#          - domain: 'localhost'
#            keyCertChainFile: '/Users/zhukunshuai/Desktop/cert/example.com+1.pem'
#            keyFile: '/Users/zhukunshuai/Desktop/cert/example.com+1-key.pem'
#          - domain: 'example.com'
#            keyCertChainFile: '/Users/zhukunshuai/Desktop/cert/example.com+1.pem'
#            keyFile: '/Users/zhukunshuai/Desktop/cert/example.com+1-key.pem'
#  httpclient:
#    strategy: netty # webClient
#    connectTimeout: 45000
#    responseTimeout: 3000
#    readerIdleTime: 3000
#    writerIdleTime: 3000
#    allIdleTime: 3000
#    readTimeout: 3000
#    writeTimeout: 3000
#    wiretap: false
#    keepAlive: false
#    maxInMemorySize: 1 #1mb
#    pool:
#      type: ELASTIC
#      name: proxy
#      maxConnections: 16
#      acquireTimeout: 45000
#      maxIdleTime: 3000 # unit: ms
#      maxLifeTime:  # unit: ms
#      evictionInterval:  # unit: ms
#      metrics: false
#    proxy:
#      host:
#      port:
#      username:
#      password:
#      nonProxyHostsPattern:
#    ssl:
#      useInsecureTrustManager: true
#      keyStoreType: PKCS12
#      keyStorePath: classpath:keystore.p12
#      keyStorePassword: 123456
#      keyStoreProvider:
#      keyPassword: 123456
#      trustedX509Certificates:
#      handshakeTimeout:
#      closeNotifyFlushTimeout:
#      closeNotifyReadTimeout:
#      defaultConfigurationType:
#    threadPool:
#      prefix: shenyu
#      selectCount: 1
#      workerCount: 8
#      daemon: true
  duplicate-response-header:
    strategy: RETAIN_FIRST
    headers:
      - Access-Control-Allow-Origin
  register:
    enabled: false
    registerType: zookeeper #etcd #consul
    serverLists: localhost:2181 #http://localhost:2379 #localhost:8848
    props:
  cross:
    enabled: true
    allowedHeaders:
    allowedMethods: "*"
    allowedAnyOrigin: true # the same of Access-Control-Allow-Origin: "*"
#    allowedOrigin:
      # format : schema://prefix spacer domain
      # Access-Control-Allow-Origin: "http://a.apache.org,http://b.apache.org"
#      spacer: "."
#      domain: apache.org
#      prefixes:
#        - a # a.apache.org
#        - b # b.apache.org
#      origins:
#        - c.apache.org
#        - d.apache.org
#        - http://e.apache.org
#      originRegex: ^http(|s)://(.*\.|)abc.com$
    allowedExpose: ""
    maxAge: "18000"
    allowCredentials: true

  switchConfig:
    local: true
    collapseSlashes: false
  file:
    enabled: true
    maxSize : 10
  sync:
    websocket:
      urls: ws://localhost:19095/websocket
      allowOrigin: ws://localhost:9195
#    apollo:
#      appId: shenyu
#      meta: http://localhost:8080
#      env: dev
#      clusterName: test
#      namespace: application
#    zookeeper:
#      url: localhost:2181
#      sessionTimeout: 5000
#      connectionTimeout: 2000
#    http:
#      url: http://localhost:9095
#      username:
#      password:
    nacos:
      url: 【nacos ip】:8848
      namespace: 【nacos命名空间】
      username: nacos
      password: nacos
      group: SHNEYU_GROUP
#      context-path: nacos
#      acm:
#        enabled: false
#        endpoint: acm.aliyun.com
#        namespace:
#        accessKey:
#        secretKey:
#    polaris:
#      url: 127.0.0.1:8093
#      namespace:
#      fileGroup:
#    etcd:
#      url: http://localhost:2379
#    consul:
#      url: http://localhost:8500
#      waitTime: 10000
#      watchDelay: 10000
  exclude:
    enabled: false
    paths:
      - /favicon.ico
  fallback:
    enabled: false
    paths:
      - /fallback/hystrix
      - /fallback/resilience4j
      - /fallback/sentinel
  health:
    enabled: true
    paths:
      - /actuator
      - /health_check
  alert:
    enabled: false
    admins: localhost:9095
  extPlugin:
    path:
    enabled: true
    threads: 1
    scheduleTime: 300
    scheduleDelay: 30
  scheduler:
    enabled: false
    type: fixed
    threads: 16
  upstreamCheck:
    enabled: false
    poolSize: 10
    timeout: 3000
    healthyThreshold: 1
    unhealthyThreshold: 1
    interval: 5000
    printEnabled: true
    printInterval: 60000
  springCloudCache:
    enabled: false
  ribbon:
    serverListRefreshInterval: 10000
  metrics:
    enabled: false
    name : prometheus
    host: 127.0.0.1
    port: 8090
    jmxConfig:
    props:
      jvm_enabled: true
#  plugins:
#    rate-limiter.enabled: false
  local:
    enabled: false
    sha512Key: "BA3253876AED6BC22D4A6FF53D8406C6AD864195ED144AB5C87621B6C233B548BAEAE6956DF346EC8C17F5EA10F35EE3CBC514797ED7DDD3145464E2A0BAB413"
  websocket:
    enableProxyPing: false
#  sharedPool:
#    enable: true
#    prefix: "shenyu-shared"
#    corePoolSize: 200
#    maximumPoolSize: 2000
#    keepAliveTime: 60000
#    # 1GB
#    maxWorkQueueMemory: 1073741824
#    # 256MB
#    maxFreeMemory: 268435456

logging:
  level:
    root: info
    org.springframework.boot: info
    org.apache.ibatis: info
    org.apache.shenyu.bonuspoint: info
    org.apache.shenyu.lottery: info
    org.apache.shenyu: info
    org.springframework.http.server.reactive: info
    org.springframework.web.reactive: info
    reactor.ipc.netty: info
    reactor.netty: info

你好:我的2025