Comprehensive use of spring cloud technology to realize microservice application

  In the previous chapters, we have implemented the configuration server, registration server, microservice server, and realized service registration and discovery. This chapter will implement the client side of the microservice, as well as jointly debug and implement the core application of the entire spring cloud framework.

  This article belongs to the fifth of the "Learning Spring Cloud Series in 7 Days", and the projects involved include:

  Open source project: http://git.oschina.net/zhou666/spring-cloud-7simple

  • cloud-config-server: configure the server
  • cloud-eureka-server: eureka registration server
  • cloud-simple-service: a database application using mybatis, server side
  • cloud-simple-ui: webui client

  Let's first take a look at how to implement a webui client. In spring boot, jsp has been deprecated, so if you use jsp to implement the webui side, it will be very troublesome. This may be related to the current mainstream development focus on mobile terminals, microservices, and the current technical needs of the entire era. Simply using html as the client has many advantages, such as being more conducive to the use of cache; making the background service stateless is more conducive to handling high concurrency; it is more conducive to the page as a service, and small services are combined into large services, etc.

  We prefer to create webui applications, refer to the git cloud-simple-ui project:

   

         This application includes front-end html pages and also includes a shallow back-end controller. This is a front-end application, why include a shallow controller layer? This is because the shallow layer of this controller is used for service composition, because a page may involve calling multiple services, and these services may involve transaction and concurrency issues, so it still needs to be done by java. Of course, you can also write an api gateway to implement this layer, you can use go, node.js language, etc., you can also use java/netty (mainstream is still java, because the development and deployment efficiency is high).

       The WebApplication of the Controller layer is the entrance of this application. The code is as follows:

  @SpringBootApplication

  @EnableEurekaClient

  @EnableHystrix

  public class WebApplication {

         public static void main(String[] args) throws Exception {

               SpringApplication.run(WebApplication.class, args);

    }

  }

  Most of these annotations have been used previously:

  @SpringBootApplication is equivalent to the combination of @Configuration, @EnableAutoConfiguration, and @ComponentScan annotations.

  @EnableEurekaClient configures this application to use service registration and service discovery, note: registration and discovery use this annotation.

  @EnableHystrix means enabling circuit breakers, circuit breakers rely on service registration and discovery.

  The service package of the Controller layer encapsulates the service interface access. The UserService class code is as follows:

  @Service

  public class UserService {

          @Autowired

    RestTemplate restTemplate; 

    final String SERVICE_NAME="cloud-simple-service";        

     @HystrixCommand(fallbackMethod = "fallbackSearchAll")

    public List<User> searchAll() {

      return restTemplate.getForObject("http://"+SERVICE_NAME+"/user", List.class);

    }   

    private List<User> fallbackSearchAll() {

               System.out.println("HystrixCommand fallbackMethod handle!");

               List<User> ls = new ArrayList<User>();

               User user = new User();

               user.setUsername("TestHystrix");

               ls.add(user);

               return ls;

    }

  }

  这里使用了断路器,就是@HystrixCommand注解。断路器的基本作用就是@HystrixCommand注解的方法失败后,系统将自动切换到fallbackMethod方法执行。断路器Hystrix具备回退机制、请求缓存和请求打包以及监控和配置等功能,在这里我们只是使用了它的核心功能:回退机制,使用该功能允许你快速失败并迅速恢复或者回退并优雅降级。

  这里使用restTemplate进行服务调用,因为使用了服务注册和发现,所以我们只需要传入服务名称SERVICE_NAME作为url的根路径,如此restTemplate就会去EurekaServer查找服务名称所代表的服务并调用。而这个服务名称就是在服务提供端cloud-simple-service中spring.application.name所配置的名字,这个名字在服务启动时连同它的IP和端口号都注册到了EurekaServer。

  封装好服务调用后,你只需要在Controller类里面注入这个服务即可:

  @RestController

  public class UserController {       

       @Autowired

       UserService userService;      

       @RequestMapping(value="/users")

       public ResponseEntity<List<User>> readUserInfo(){

              List<User> users=userService.searchAll();         

              return new ResponseEntity<List<User>>(users,HttpStatus.OK);

       }

  }

  至此这个webui应用的java端就开发完了,我们再来看页面模块。

  可以看到,页面文件都放在resources\static目录下面,这是spring boot默认的页面文件主文件夹,你如果在里面放一个index.html,那么直接访问根路径http://localhost:8080/会直接定位到这个页面。所以这个static就相当于传统web项目里面的webapp文件夹。

  在这里包括两个页面index.html和user-page.html,用户访问首页时将会加载user-page.html子页面。

  首页index.html页面核心代码如下:

  <html ng-app="users">

  <head>   

    <script src="js/app.js"></script>

  </head>

  <body>

  <div ng-view class="container">

  </div>

  </body>

  </html>

  页面user-page.html代码如下:

  <div>

  <ul ng-controller="userCtr">

    <li ng-repeat="item in userList">

  {{item.username}}   

  </li>

  </ul>

  </div>

  app.js页面代码如下:

  angular.module('users', ['ngRoute']).config(function ($routeProvider) {

  $routeProvider.when('/', {

        templateUrl: 'user-page.html',

        controller: 'userCtr'

  })

  }).controller('userCtr', function ($scope, $http) {

  $http.get('users').success(function (data) {

           //alert(data+"");

        $scope.userList = data;

  });

  });

  这里使用了angularJS库。Angular可以绑定模型数据到页面变量,在user-page.html看到的{{item.username}}就是它的绑定语法,这个语法根jsp或freemarker这些模板技术都类似,只不过Angular是用在客户端的,而前者是用在服务端的。

  至此这个webui应用就开发完了,改一下配置文件和pom文件就可以运行了。配置文件包括配置管理服务器地址,注册服务器地址等,在bootstrap.properties文件中:

  spring.cloud.config.uri=http://127.0.0.1:${config.port:8888}

  spring.cloud.config.name=cloud-config

  spring.cloud.config.profile=${config.profile:dev}

  eureka.client.serviceUrl.defaultZone=http\://localhost\:8761/eureka/

  spring.application.name=simple-ui-phone

  这些配置我们在上一章已经提到过了,这里不再解释。因为使用了断路器,所以相比上一章的cloud-simple-service项目,需要加入hystrix依赖,只有一个starter依赖:

  <dependency>

    <groupId>org.springframework.cloud</groupId>

  <artifactId>spring-cloud-starter-hystrix</artifactId>

  </dependency>

  Spring把事情做的如此简单,不管是服务注册还是断路器,连同注解加配置文件再加上依赖总共不超过十行代码。如此简单就可以使用一个分布式应用,也难怪国内外业内人员都高度重视这个框架,在简单和速度就是硬道理的今天,这个框架有着重要的意义。

   剩下最重要的事情就是进行部署了,我们以此使用命令启动这些服务及应用:

  1)  java -jar cloud-config-server-0.0.1.jar,启动配置服务器,固定绑定端口8888;

  2)  java -jar cloud-eureka-server-1.0.0.jar,启动注册服务器,固定绑定端口8671;

  3)  java -jar cloud-simple-service-1.0.0.jar --server.port=8081 >log8081.log,启动后台服务,绑定端口8081

  4)  java -jar cloud-simple-service-1.0.0.jar --server.port=8082 >log8082.log,启动后台服务,绑定端口8082

  5)  java -jar cloud-simple-ui-1.0.0.jar --server.port=8080 >log8080.log,启动前端ui应用,绑定端口8080

  运行http://localhost:8080/即可看到运行的结果。其中“>log8080.log”表示输出日志到文件。

  这里运行了两个cloud-simple-service实例,主要是为了演示ribbon负载均衡。默认情况下使用ribbon不需要再作任何配置,不过它依赖于注册服务器。当然也可以对ribbon进行一些自定义设置,比如配置它的超时时间、重试次数等。启用了负载均衡后,当我们关掉前端页面上次指向的服务时(从日志中看),比如我们刷新页面看到它调用的是8081服务,那么我们关掉这个服务。关掉后再刷新会发现执行了断路器,过几秒再刷新,它已经切换到了8082这台服务器,这说明负载均衡起作用了。

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326448282&siteId=291194637