zoukankan      html  css  js  c++  java
  • 使用Spring Cloud Gateway搭建游戏服务网关(2)

    接着上篇文章来说:使用Spring Cloud Gateway搭建游戏服务网关(1)
    在上篇文章中我们创建了Spring Cloud Gateway的一个网关项目,要启动这个项目,需要添加一下main该当,如下面代码所示:

    @SpringBootApplication
    @EnableDiscoveryClient
    public class WebGatewayMain {
    
        public static void main(String[] args) {
            System.setProperty("reactor.netty.http.server.accessLogEnabled", "true");
            SpringApplication.run(WebGatewayMain.class, args);
        }
    }
    

    这个注解@EnableDiscoveryClient就是启用服务发现客户端,它会在网关服务启动之后,自动去服务注册中心服务定时获取已注册的服务信息,并自动在网关这里配置相关的路由信息。

    下面我们再添加一个服务项目,比如用户服务项目:game-web-user,然后在项目中添加配置文件:application.yml,如下面所示:

    logging:
      config: classpath:log4j2.xml
    server:
      port: 9002
     
    spring:
      application:
        name: game-web-user
      cloud:
        consul:
          host: localhost  # 服务治理服务的地址
          port: 7777      # 服务治理服务的端口
          discovery:
            prefer-ip-address: true
            ip-address: 127.0.0.1   # 此服务所在的服务器ip地址
            catalog-services-watch-delay: 10000
            health-check-critical-timeout: 60s    # 注册成功之后,如果关闭此服务,consul将检测60s,如果60s之后还检测不到此服务,将会把此服务从注册列表中移除
            
    

    这里的配置有两个重要的信息,一是,服务的名字,即spring.applicaton.name,它会在网关处被用做服务的ServiceID,二是,discovery里面的配置 ,它表示将此服务在服务启动的时候自动注册到服务治理中心Consul服务中。

    然后在game-web-user项目的pom.xml中添加依赖:

      <dependencies>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-web</artifactId>
    		</dependency>
    	</dependencies>
    

    其它的依赖都添加到父类项目中了,详细的可以参考源码项目:https://gitee.com/wgslucky/SpringCloud

    然后添加Main方法,如下面代码所示:

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

    为了测试请求的转发,在game-web-user的项目中添加 UserController,并添加一个接收请求的方法 ,如下面代码所示:

    @RestController
    @RequestMapping("user")
    public class UserController {
    
    	@RequestMapping("getUser")
    	public Object getUser() {
    		JSONObject user = new JSONObject();
    		user.put("name", "www.xinyues.com");
    		return user;
    	}
    }
    

    然后分另启动Consul服务,game-web-user项目,spring-cloud-gateway项目,记得把spring-cloud-gateway项目中的application.yml的active修改为auto。然后在浏览器中输入:
    http://localhost:8081/game-web-user/user/getUser,可以看到浏览器中输出了game-web-user项目返回的内容。说明网关转发浏览器请求成功了。,这里面的game-web-user就是在它项目中配置的spring.applcation.name的值,如果网关后面有多个服务,可以根据它来区分不同的服务。从这里可以看到,使用Spring Cloud开发配置一个分式服务如此的简单方便。

  • 相关阅读:
    C# 对Outlook2010进行二次开发
    利用AForge.NET 调用电脑摄像头进行拍照
    SQL2012 提示评估已过期 解决方案- sql server问题
    图片转换PDF
    [转载]理解weight decay
    ATTENTION NETWORK分析
    sys.stdout.write和print和sys.stdout.flush
    Flutter免费(视频)教程汇总
    Windows核心编程随笔
    .NET家族
  • 原文地址:https://www.cnblogs.com/wgslucky/p/11750148.html
Copyright © 2011-2022 走看看