草庐IT

记录一: Spring Cloud Alibaba 2021.X 搭建

zy115 2023-04-02 原文

一   》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》

下载nacos    https://github.com/alibaba/nacos      nacos-server-2.0.3.zip   Windows 版 

解压后,数据库新建nacos库,将 X:\nacos\conf 目录下的 nacos-mysql.sql 文件执行 导入数据表与数据

修改文件 X:\nacos\conf 目录下 application.properties 

 1 #*************** Config Module Related Configurations ***************#
 2 ### If use MySQL as datasource:
 3 spring.datasource.platform=mysql
 4 
 5 ### Count of DB:
 6 db.num=1
 7 
 8 ### Connect URL of DB:
 9 db.url.0=jdbc:mysql://127.0.0.1:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC
10 db.user.0=root
11 db.password.0=Root!234

修改文件 X:\nacos\bin 目录下的 startup.cmd  标红部分 为单机模式

set BASE_DIR="%BASE_DIR:~0,-5%"

set CUSTOM_SEARCH_LOCATIONS=file:%BASE_DIR%/conf/

set MODE="standalone"   rem “cluster”
set FUNCTION_MODE="all"
set SERVER=nacos-server
set MODE_INDEX=-1
set FUNCTION_MODE_INDEX=-1
set SERVER_INDEX=-1
set EMBEDDED_STORAGE_INDEX=-1
set EMBEDDED_STORAGE=""

双击启动 startup.cmd  第一行显示   "nacos is starting with standalone"  为单机模式

"nacos is starting with standalone"

         ,--.
       ,--.'|
   ,--,:  : |                                           Nacos 2.0.3
,`--.'`|  ' :                       ,---.               Running in stand alone mode, All function modules
|   :  :  | |                      '   ,'\   .--.--.    Port: 8848
:   |   \ | :  ,--.--.     ,---.  /   /   | /  /    '   Pid: 7892
|   : '  '; | /       \   /     \.   ; ,. :|  :  /`./   Console: http://127.0.0.1:8848/nacos/index.html
'   ' ;.    ;.--.  .-. | /    / ''   | |: :|  :  ;_
|   | | \   | \__\/: . ..    ' / '   | .; : \  \    `.      https://nacos.io
'   : |  ; .' ," .--.; |'   ; :__|   :    |  `----.   \
|   | '`--'  /  /  ,.  |'   | '.'|\   \  /  /  /`--'  /
'   : |     ;  :   .'   \   :    : `----'  '--'.     /
;   |.'     |  ,     .-./\   \  /            `--'---'
'---'        `--`---'     `----'

2023-04-02 08:56:24,132 INFO Bean 'org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler@2392212b' of type [org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

2023-04-02 08:56:24,138 INFO Bean 'methodSecurityMetadataSource' of type [org.springframework.security.access.method.DelegatingMethodSecurityMetadataSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

2023-04-02 08:56:24,746 INFO Tomcat initialized with port(s): 8848 (http)

2023-04-02 08:56:25,248 INFO Root WebApplicationContext: initialization completed in 7616 ms

2023-04-02 08:56:30,342 INFO Initializing ExecutorService 'applicationTaskExecutor'

2023-04-02 08:56:30,512 INFO Adding welcome page: class path resource [static/index.html]

2023-04-02 08:56:31,244 INFO Creating filter chain: Ant [pattern='/**'], []

2023-04-02 08:56:31,299 INFO Creating filter chain: any request, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@29f85fe1, org.springframework.security.web.context.SecurityContextPersistenceFilter@73d3e555, org.springframework.security.web.header.HeaderWriterFilter@bbf9e07, org.springframework.security.web.csrf.CsrfFilter@2af46afd, org.springframework.security.web.authentication.logout.LogoutFilter@3a08078c, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@44924587, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@4487c0c2, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@43a0a32d, org.springframework.security.web.session.SessionManagementFilter@2b289ac9, org.springframework.security.web.access.ExceptionTranslationFilter@31ceba99]

2023-04-02 08:56:31,483 INFO Initializing ExecutorService 'taskScheduler'

2023-04-02 08:56:31,501 INFO Exposing 16 endpoint(s) beneath base path '/actuator'

2023-04-02 08:56:31,638 INFO Tomcat started on port(s): 8848 (http) with context path '/nacos'

2023-04-02 08:56:31,641 INFO Nacos started successfully in stand alone mode. use external storage

2023-04-02 08:56:45,175 INFO Initializing Servlet 'dispatcherServlet'

2023-04-02 08:56:45,189 INFO Completed initialization in 13 ms

 

 

访问 http://localhost:8848/nacos/index.html    账号密码为 nacos   

 

二  》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》

 1.idea新建springboot项目《cloud》,保留  .idea    pom.xml   两个 ,其余全部删除。

  修改pom.xml 文件   注意jdk版本对应springboot版本,springboot版本对应的springcloud版本 

  • 2022.x 分支对应的是 Spring Cloud 2022 与 Spring Boot 3.0.x,最低支持 JDK 17。
  • 2021.x 分支对应的是 Spring Cloud 2021 与 Spring Boot 2.6.x,最低支持 JDK 1.8。
  • 2020.0 分支对应的是 Spring Cloud 2020 与 Spring Boot 2.4.x,最低支持 JDK 1.8。
  • 2.2.x 分支对应的是 Spring Cloud Hoxton 与 Spring Boot 2.2.x,最低支持 JDK 1.8。
  • greenwich 分支对应的是 Spring Cloud Greenwich 与 Spring Boot 2.1.x,最低支持 JDK 1.8。
  • finchley 分支对应的是 Spring Cloud Finchley 与 Spring Boot 2.0.x,最低支持 JDK 1.8。
  • 1.x 分支对应的是 Spring Cloud Edgware 与 Spring Boot 1.x,最低支持 JDK 1.7。
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
 4     <modelVersion>4.0.0</modelVersion>
 5     <parent>
 6         <groupId>org.springframework.boot</groupId>
 7         <artifactId>spring-boot-starter-parent</artifactId>
 8         <version>2.6.10</version>
 9         <relativePath/> <!-- lookup parent from repository -->
10     </parent>
11     <groupId>com.example</groupId>
12     <artifactId>cloud</artifactId>
13     <version>0.0.1-SNAPSHOT</version>
14     <name>cloud</name>
15     <description>cloud</description>
16 
17     <packaging>pom</packaging>
18 
19     <properties>
20         <java.version>1.8</java.version>
21         <spring-cloud-alibaba-dependencies-version>2021.0.5.0</spring-cloud-alibaba-dependencies-version>
22     </properties>
23 
24     <dependencies>
25         <dependency>
26             <groupId>org.springframework.boot</groupId>
27             <artifactId>spring-boot-starter</artifactId>
28         </dependency>
29         <dependency>
30             <groupId>org.springframework.boot</groupId>
31             <artifactId>spring-boot-starter-web</artifactId>
32         </dependency>
33         <dependency>
34             <groupId>org.springframework.boot</groupId>
35             <artifactId>spring-boot-starter-test</artifactId>
36             <scope>test</scope>
37             <exclusions>
38                 <exclusion>
39                     <groupId>org.junit.vintage</groupId>
40                     <artifactId>junit-vintage-engine</artifactId>
41                 </exclusion>
42             </exclusions>
43         </dependency>
44     </dependencies>
45 
46     <build>
47         <plugins>
48             <plugin>
49                 <groupId>org.springframework.boot</groupId>
50                 <artifactId>spring-boot-maven-plugin</artifactId>
51             </plugin>
52         </plugins>
53     </build>
54 
55     <dependencyManagement>
56         <dependencies>
57             <dependency>
58                 <groupId>com.alibaba.cloud</groupId>
59                 <artifactId>spring-cloud-alibaba-dependencies</artifactId>
60                 <version>${spring-cloud-alibaba-dependencies-version}</version>
61                 <type>pom</type>
62                 <scope>import</scope>
63             </dependency>
64         </dependencies>
65     </dependencyManagement>
66 </project>

 

   2.新建在cloud项目下 新建 maven model 《provider》  注意是maven项目 

    修改pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.example</groupId>
        <artifactId>cloud</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>

    <groupId>cn.com.provider</groupId>
    <artifactId>provider</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
    </dependencies>
</project>

  新建 java项目目录与application启动类

 

application.yam文件内容如下

server:
  port: 8001
spring:
  application:
    name: provider
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848

ProviderApplication.class 文件内容如下 (注意标红部分)

package cn.com.provider;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class ProviderApplication {

    public static void main(String[] args) {
        SpringApplication.run(ProviderApplication.class, args);
    }

}

创建一个TestController.class  (ResultUtil.result()我自己创建的返回封装,不重要,写个字符串就“provider success” 就好!)

package cn.com.provider.controller;

import cn.com.kity.common.result.ResultUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/test")
public class TestController {

    @GetMapping(value = "/test01")
    public Object eg01(){
    //provider success return ResultUtil.result(); } }

启动provider 访问 localhost:8001/test/test01  返回    provider success

nacos服务管理下服务列表出现provider服务

  3.同上创建consumer服务【maven项目】  consumer服务需要调用provider服务 则使用Feign交互

目录结构为:

 

 

pom.xml如下: 多了三个    openfeign;  loadbalancer;  sentinel;

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <project xmlns="http://maven.apache.org/POM/4.0.0"
 3          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 5     <modelVersion>4.0.0</modelVersion>
 6     <parent>
 7         <groupId>com.example</groupId>
 8         <artifactId>cloud</artifactId>
 9         <version>0.0.1-SNAPSHOT</version>
10     </parent>
11 
12     <artifactId>consumer</artifactId>
13 
14     <properties>
15         <maven.compiler.source>8</maven.compiler.source>
16         <maven.compiler.target>8</maven.compiler.target>
17         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
18     </properties>
19     <dependencies>
20         <dependency>
21             <groupId>com.alibaba.cloud</groupId>
22             <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
23         </dependency>
24         <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-openfeign -->
25         <dependency>
26             <groupId>org.springframework.cloud</groupId>
27             <artifactId>spring-cloud-starter-openfeign</artifactId>
28             <version>3.1.6</version>
29         </dependency>
30         <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-loadbalancer -->
31         <dependency>
32             <groupId>org.springframework.cloud</groupId>
33             <artifactId>spring-cloud-loadbalancer</artifactId>
34             <version>3.1.6</version>
35         </dependency>
36         <!-- https://mvnrepository.com/artifact/com.alibaba.cloud/spring-cloud-starter-alibaba-sentinel -->
37         <dependency>
38             <groupId>com.alibaba.cloud</groupId>
39             <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
40             <exclusions> <!--除去该依赖,controller返回的结果才是json,不去除就xml-->
41                 <exclusion>
42                 <groupId>com.fasterxml.jackson.dataformat</groupId>
43                     <artifactId>jackson-dataformat-xml</artifactId>
44                 </exclusion>
45             </exclusions>
46         </dependency>
47     </dependencies>
48 </project>

application.yml内容如下:

 1 server:
 2   port: 8002
 3 spring:
 4   application:
 5     name: consumer
 6   cloud:
 7     nacos:
 8       discovery:
 9         server-addr: 127.0.0.1:8848
10 feign:
11   sentinel:
12     enabled: true #开启feign对sentinel的支持 服务降级

 

创建ConsumerApplication.class 内容如下:【注意标红部分】

package cn.com.consumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

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

}

创建FeignFallBack.class 内容如下:

package cn.com.consumer.feign;



import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component;

@Component
public class FeignFallBack implements FallbackFactory<ConsumerFeignToProvider> {
    @Override
    public ConsumerFeignToProvider create(Throwable cause) {
        return () -> "provider 服务提供者挂了!!!!!!";
    }
}

 

创建ConsumerFeignToProvider.class内容如下:

标红地方为provider服务名称,

application.yml中

spring:
  application:
    name: provider
package cn.com.consumer.feign;


import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

@FeignClient(name = "provider",fallbackFactory = FeignFallBack.class)
public interface ConsumerFeignToProvider {

    @GetMapping("/test/test01")
    String test01();

}

 

创建TestController.class内容如下

 1 package cn.com.consumer.controller;
 2 
 3 import cn.com.consumer.feign.ConsumerFeignToProvider;
 4 import org.springframework.web.bind.annotation.GetMapping;
 5 import org.springframework.web.bind.annotation.RequestMapping;
 6 import org.springframework.web.bind.annotation.RestController;
 7 
 8 import javax.annotation.Resource;
 9 
10 @RestController
11 @RequestMapping(value = "/consumer")
12 public class TestController {
13 
14     @Resource
15     ConsumerFeignToProvider cftp;
16 
17     @GetMapping(value = "/eg01")
18     public Object eg01(){
19         return "consumer01 掉用 ===" + cftp.test01() ;
20     }
21 
22 }

启动consumer服务:

nacos服务管理下服务列表出现consumer服务

访问http://localhost:8002/consumer/eg01 返回

consumer01 掉用 ===provider success

停止provider服务  访问http://localhost:8002/consumer/eg01 返回

consumer01 掉用 ===provider 服务提供者挂了!!!!!!

 

====================================================结束===================================================gateway+++conifg======================================================

有关记录一: Spring Cloud Alibaba 2021.X 搭建的更多相关文章

  1. ruby - Sinatra:运行 rspec 测试时记录噪音 - 2

    Sinatra新手;我正在运行一些rspec测试,但在日志中收到了一堆不需要的噪音。如何消除日志中过多的噪音?我仔细检查了环境是否设置为:test,这意味着记录器级别应设置为WARN而不是DEBUG。spec_helper:require"./app"require"sinatra"require"rspec"require"rack/test"require"database_cleaner"require"factory_girl"set:environment,:testFactoryGirl.definition_file_paths=%w{./factories./test/

  2. ruby-on-rails - Rails 5 Active Record 记录无效错误 - 2

    我有两个Rails模型,即Invoice和Invoice_details。一个Invoice_details属于Invoice,一个Invoice有多个Invoice_details。我无法使用accepts_nested_attributes_forinInvoice通过Invoice模型保存Invoice_details。我收到以下错误:(0.2ms)BEGIN(0.2ms)ROLLBACKCompleted422UnprocessableEntityin25ms(ActiveRecord:4.0ms)ActiveRecord::RecordInvalid(Validationfa

  3. ruby-on-rails - 事件记录 : Select max of limit - 2

    我正在尝试将以下SQL查询转换为ActiveRecord,它正在融化我的大脑。deletefromtablewhereid有什么想法吗?我想做的是限制表中的行数。所以,我想删除少于最近10个条目的所有内容。编辑:通过结合以下几个答案找到了解决方案。Temperature.where('id这给我留下了最新的10个条目。 最佳答案 从您的SQL来看,您似乎想要从表中删除前10条记录。我相信到目前为止的大多数答案都会如此。这里有两个额外的选择:基于MurifoX的版本:Table.where(:id=>Table.order(:id).

  4. Ruby 守护进程导致 ActiveRecord 记录器 IOError - 2

    我目前正在用Ruby编写一个项目,它使用ActiveRecordgem进行数据库交互,我正在尝试使用ActiveRecord::Base.logger记录所有数据库事件具有以下代码的属性ActiveRecord::Base.logger=Logger.new(File.open('logs/database.log','a'))这适用于迁移等(出于某种原因似乎需要启用日志记录,因为它在禁用时会出现NilClass错误)但是当我尝试运行包含调用ActiveRecord对象的线程守护程序的项目时脚本失败并出现以下错误/System/Library/Frameworks/Ruby.frame

  5. ruby-on-rails - 在 Rails 中更高效地查找或创建多条记录 - 2

    我有一个应用需要发送用户事件邀请。当用户邀请friend(用户)参加事件时,如果尚不存在将用户连接到该事件的新记录,则会创建该记录。我的模型由用户、事件和events_user组成。classEventdefinvite(user_id,*args)user_id.eachdo|u|e=EventsUser.find_or_create_by_event_id_and_user_id(self.id,u)e.save!endendend用法Event.first.invite([1,2,3])我不认为以上是完成我的任务的最有效方法。我设想了一种方法,例如Model.find_or_cr

  6. ruby - 在模块/类之间共享全局记录器 - 2

    在许多ruby​​类之间共享记录器实例的最佳(正确)方法是什么?现在我只是将记录器创建为全局$logger=Logger.new变量,但我觉得有更好的方法可以在不使用全局变量的情况下执行此操作。如果我有以下内容:moduleFooclassAclassBclassC...classZend在所有类之间共享记录器实例的最佳方式是什么?我是以某种方式在Foo模块中声明/创建记录器还是只是使用全局$logger没问题? 最佳答案 在模块中添加常量:moduleFooLogger=Logger.newclassAclassBclassC..

  7. ruby - Sinatra 中的全局救援和日志记录异常 - 2

    如何在出现异常时指定全局救援,如果您将Sinatra用于API或应用程序,您将如何处理日志记录? 最佳答案 404可以在not_found方法的帮助下处理,例如:not_founddo'Sitedoesnotexist.'end500s可以通过调用带有block的错误方法来处理,例如:errordo"Applicationerror.Plstrylater."end错误的详细信息可以通过request.env中的sinatra.error访问,如下所示:errordo'Anerroroccured:'+request.env['si

  8. ruby-on-rails - 在不重新查询数据库的情况下重新排序 Rails 中的事件记录? - 2

    例如,假设我有一个名为Products的模型,并且在ProductsController中,我有以下代码用于product_listView以显示已排序的产品。@products=Product.order(params[:order_by])让我们想象一下,在product_listView中,用户可以使用下拉菜单按价格、评级、重量等进行排序。数据库中的产品不会经常更改。我很难理解的是,每次用户选择新的order_by过滤器时,rails是否必须查询,或者rails是否能够以某种方式缓存事件记录以在服务器端重新排序?有没有一种方法可以编写它,以便在用户排序时rails不会重新查询结果

  9. ruby-on-rails - ActiveRecord 如何将现有记录添加到 has_many :through relationship in rails? 中的关联 - 2

    在我的Rails项目中,我有三个模型:classRecipe:recipe_categorizationsaccepts_nested_attributes_for:recipe_categories,allow_destroy::trueendclassCategory:recipe_categorizationsendclassRecipeCategorization通过这个简单的has_many:through设置,我怎样才能像这样获取给定的食谱:@recipe=Recipe.first并根据现有类别向此食谱添加类别,并在相应类别上对其进行更新。所以:@category=#Exi

  10. ruby-on-rails - 使用 Rails 事件记录获取二级模型 - 2

    我有一个帖子属于城市的关系,城市又属于一个州,例如:classPost现在我想找到所有帖子及其所属的城市和州。我编写了以下查询来获取带有城市的帖子,但不知道如何在同一查找器中获取带有城市的相应州:@post=Post.find:all,:include=>[:city]感谢任何帮助。谢谢。 最佳答案 Post.all(:include=>{:city=>:state}) 关于ruby-on-rails-使用Rails事件记录获取二级模型,我们在StackOverflow上找到一个类似的问

随机推荐