Sentinel 系统规则规则持久化( push模式 Nacos)

上一篇Sentinel 流控规则规则
Sentinel下载地址(已修改)

  1. 修改应用服务的application.yml
    在这里插入图片描述
        system:
          nacos:
            server-addr: localhost:8848 # nacos地址
            dataId: orderservice-system-rules
            groupId: SENTINEL_GROUP
            rule-type: system # 还可以是:degrade、authority、param-flowparam-flow
  1. 修改NacosConfigUtil.java,添加代码
 /**
     * 系统规格
     */
    public static final String SYSTEM_DATA_ID_POSTFIX = "-system-rules";

  1. 新增com\alibaba\csp\sentinel\dashboard\rule\nacos\SystemRuleNacosProvider.java
    在这里插入图片描述
package com.alibaba.csp.sentinel.dashboard.rule.nacos;

import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.DegradeRuleEntity;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.SystemRuleEntity;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.nacos.api.config.ConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * Sentinel 系统规则 持久化  Push 模式 Nacos
 * @Author jianghx
 * @Date 2021/12/24 11:47
 * @Version 1.0
 **/
@Component("systemRuleNacosProvider")
public class SystemRuleNacosProvider implements DynamicRuleProvider<List<SystemRuleEntity>> {

    @Autowired
    private ConfigService configService;

    @Autowired
    private Converter<String, List<SystemRuleEntity>> converter;

    @Override
    public List<SystemRuleEntity> getRules(String appName) throws Exception {
        String rules = configService.getConfig(appName + NacosConfigUtil.SYSTEM_DATA_ID_POSTFIX,
                NacosConfigUtil.GROUP_ID, 3000);
        if (StringUtil.isEmpty(rules)) {
            return new ArrayList<>();
        }
        return converter.convert(rules);
    }
}

  • 修改 com\alibaba\csp\sentinel\dashboard\rule\nacos\NacosConfig.java

在这里插入图片描述

   @Bean
    public Converter<List<SystemRuleEntity>, String> systemRuleEntityEncoder() {
        return JSON::toJSONString;
    }

    @Bean
    public Converter<String, List<SystemRuleEntity>> systemRuleEntityDecoder() {
        return s -> JSON.parseArray(s, SystemRuleEntity.class);
    }

  • 新增com\alibaba\csp\sentinel\dashboard\rule\nacos\SystemRuleNacosPublisher.java
package com.alibaba.csp.sentinel.dashboard.rule.nacos;


import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.SystemRuleEntity;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher;
import com.alibaba.csp.sentinel.util.AssertUtil;
import com.alibaba.nacos.api.config.ConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.alibaba.csp.sentinel.datasource.Converter;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * Sentinel 系统规则 持久化  Push 模式 Nacos
 * @Author jianghx
 * @Date 2021/12/24 11:47
 * @Version 1.0
 **/
@Component("systemRuleNacosPublisher")
public class SystemRuleNacosPublisher implements DynamicRulePublisher<List<SystemRuleEntity>>
{

    @Autowired
    private ConfigService configService;
    @Autowired
    private Converter<List<SystemRuleEntity>, String> converter;

    @Override
    public CompletableFuture<Void> publish(String app, List<SystemRuleEntity> rules) throws Exception {
        AssertUtil.notEmpty(app, "app name cannot be empty");
        if (rules == null) {
            return null;
        }
        configService.publishConfig(app + NacosConfigUtil.SYSTEM_DATA_ID_POSTFIX,
                NacosConfigUtil.GROUP_ID, converter.convert(rules));
        return null;
    }
}

  • 新增com\alibaba\csp\sentinel\dashboard\controller\v2\SystemControllerV2.java
    在这里插入图片描述
/*
 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed 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.
 */
package com.alibaba.csp.sentinel.dashboard.controller.v2;

import com.alibaba.csp.sentinel.dashboard.auth.AuthAction;
import com.alibaba.csp.sentinel.dashboard.auth.AuthService.PrivilegeType;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.SystemRuleEntity;
import com.alibaba.csp.sentinel.dashboard.discovery.MachineInfo;
import com.alibaba.csp.sentinel.dashboard.domain.Result;
import com.alibaba.csp.sentinel.dashboard.repository.rule.RuleRepository;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher;
import com.alibaba.csp.sentinel.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * Sentinel 系统规则 持久化  Push 模式 Nacos
 *
 * @Author jianghx
 * @Date 2021/12/27 10:30
 * @Version 1.0
 **/
@RestController
@RequestMapping("/v2/system")
public class SystemControllerV2 {

    private final Logger logger = LoggerFactory.getLogger(SystemControllerV2.class);

    @Autowired
    private RuleRepository<SystemRuleEntity, Long> repository;

    @Autowired
    @Qualifier("systemRuleNacosProvider")
    private DynamicRuleProvider<List<SystemRuleEntity>> ruleProvider;

    @Autowired
    @Qualifier("systemRuleNacosPublisher")
    private DynamicRulePublisher<List<SystemRuleEntity>> rulePublisher;

    private <R> Result<R> checkBasicParams(String app, String ip, Integer port) {
        if (StringUtil.isEmpty(app)) {
            return Result.ofFail(-1, "app can't be null or empty");
        }
        if (StringUtil.isEmpty(ip)) {
            return Result.ofFail(-1, "ip can't be null or empty");
        }
        if (port == null) {
            return Result.ofFail(-1, "port can't be null");
        }
        if (port <= 0 || port > 65535) {
            return Result.ofFail(-1, "port should be in (0, 65535)");
        }
        return null;
    }

    @GetMapping("/rules.json")
    @AuthAction(PrivilegeType.READ_RULE)
    public Result<List<SystemRuleEntity>> apiQueryMachineRules(String app, String ip,
                                                               Integer port) {
        Result<List<SystemRuleEntity>> checkResult = checkBasicParams(app, ip, port);
        if (checkResult != null) {
            return checkResult;
        }
        try {
            List<SystemRuleEntity> rules = ruleProvider.getRules(app);
            if (rules != null && !rules.isEmpty()) {
                for (SystemRuleEntity entity : rules) {
                    entity.setApp(app);
                }
            }
            rules = repository.saveAll(rules);
            return Result.ofSuccess(rules);
        } catch (Throwable throwable) {
            logger.error("Query machine system rules error", throwable);
            return Result.ofThrowable(-1, throwable);
        }
    }

    private int countNotNullAndNotNegative(Number... values) {
        int notNullCount = 0;
        for (int i = 0; i < values.length; i++) {
            if (values[i] != null && values[i].doubleValue() >= 0) {
                notNullCount++;
            }
        }
        return notNullCount;
    }

    @RequestMapping("/new.json")
    @AuthAction(PrivilegeType.WRITE_RULE)
    public Result<SystemRuleEntity> apiAdd(String app, String ip, Integer port,
                                           Double highestSystemLoad, Double highestCpuUsage, Long avgRt,
                                           Long maxThread, Double qps) {

        Result<SystemRuleEntity> checkResult = checkBasicParams(app, ip, port);
        if (checkResult != null) {
            return checkResult;
        }

        int notNullCount = countNotNullAndNotNegative(highestSystemLoad, avgRt, maxThread, qps, highestCpuUsage);
        if (notNullCount != 1) {
            return Result.ofFail(-1, "only one of [highestSystemLoad, avgRt, maxThread, qps,highestCpuUsage] "
                    + "value must be set > 0, but " + notNullCount + " values get");
        }
        if (null != highestCpuUsage && highestCpuUsage > 1) {
            return Result.ofFail(-1, "highestCpuUsage must between [0.0, 1.0]");
        }
        SystemRuleEntity entity = new SystemRuleEntity();
        entity.setApp(app.trim());
        entity.setIp(ip.trim());
        entity.setPort(port);
        // -1 is a fake value
        if (null != highestSystemLoad) {
            entity.setHighestSystemLoad(highestSystemLoad);
        } else {
            entity.setHighestSystemLoad(-1D);
        }

        if (null != highestCpuUsage) {
            entity.setHighestCpuUsage(highestCpuUsage);
        } else {
            entity.setHighestCpuUsage(-1D);
        }

        if (avgRt != null) {
            entity.setAvgRt(avgRt);
        } else {
            entity.setAvgRt(-1L);
        }
        if (maxThread != null) {
            entity.setMaxThread(maxThread);
        } else {
            entity.setMaxThread(-1L);
        }
        if (qps != null) {
            entity.setQps(qps);
        } else {
            entity.setQps(-1D);
        }
        Date date = new Date();
        entity.setGmtCreate(date);
        entity.setGmtModified(date);
        try {
            entity = repository.save(entity);
            publishRules(entity.getApp());
        } catch (Throwable throwable) {
            logger.error("Add SystemRule error", throwable);
            return Result.ofThrowable(-1, throwable);
        }
//        if (!publishRules(app, ip, port)) {
//            logger.warn("Publish system rules fail after rule add");
//        }
        return Result.ofSuccess(entity);
    }

    @GetMapping("/save.json")
    @AuthAction(PrivilegeType.WRITE_RULE)
    public Result<SystemRuleEntity> apiUpdateIfNotNull(Long id, String app, Double highestSystemLoad,
                                                       Double highestCpuUsage, Long avgRt, Long maxThread, Double qps) {
        if (id == null) {
            return Result.ofFail(-1, "id can't be null");
        }
        SystemRuleEntity entity = repository.findById(id);
        if (entity == null) {
            return Result.ofFail(-1, "id " + id + " dose not exist");
        }

        if (StringUtil.isNotBlank(app)) {
            entity.setApp(app.trim());
        }
        if (highestSystemLoad != null) {
            if (highestSystemLoad < 0) {
                return Result.ofFail(-1, "highestSystemLoad must >= 0");
            }
            entity.setHighestSystemLoad(highestSystemLoad);
        }
        if (highestCpuUsage != null) {
            if (highestCpuUsage < 0) {
                return Result.ofFail(-1, "highestCpuUsage must >= 0");
            }
            if (highestCpuUsage > 1) {
                return Result.ofFail(-1, "highestCpuUsage must <= 1");
            }
            entity.setHighestCpuUsage(highestCpuUsage);
        }
        if (avgRt != null) {
            if (avgRt < 0) {
                return Result.ofFail(-1, "avgRt must >= 0");
            }
            entity.setAvgRt(avgRt);
        }
        if (maxThread != null) {
            if (maxThread < 0) {
                return Result.ofFail(-1, "maxThread must >= 0");
            }
            entity.setMaxThread(maxThread);
        }
        if (qps != null) {
            if (qps < 0) {
                return Result.ofFail(-1, "qps must >= 0");
            }
            entity.setQps(qps);
        }
        Date date = new Date();
        entity.setGmtModified(date);
        try {
            entity = repository.save(entity);
        } catch (Throwable throwable) {
            logger.error("save error:", throwable);
            return Result.ofThrowable(-1, throwable);
        }
//        if (!publishRules(entity.getApp())) {
//            logger.info("publish system rules fail after rule update");
//        }
        return Result.ofSuccess(entity);
    }

    @RequestMapping("/delete.json")
    @AuthAction(PrivilegeType.DELETE_RULE)
    public Result<?> delete(Long id) {
        if (id == null) {
            return Result.ofFail(-1, "id can't be null");
        }
        SystemRuleEntity oldEntity = repository.findById(id);
        if (oldEntity == null) {
            return Result.ofSuccess(null);
        }
        try {
            repository.delete(id);
        } catch (Throwable throwable) {
            logger.error("delete error:", throwable);
            return Result.ofThrowable(-1, throwable);
        }
//        if (!publishRules(oldEntity.getApp())) {
//            logger.info("publish system rules fail after rule delete");
//        }
        return Result.ofSuccess(id);
    }

    private CompletableFuture<Void> publishRules(String app) throws Exception {
        List<SystemRuleEntity> rules = repository.findAllByApp(app);
        return rulePublisher.publish(app, rules);
    }
}

  • 修改resources\app\scripts\directives\sidebar\sidebar.html
    在这里插入图片描述
  <li ui-sref-active="active" ng-if="entry.appType==0">
            <a ui-sref="dashboard.system2({app: entry.app})">
              <i class="glyphicon glyphicon-filter"></i>&nbsp;&nbsp;系统规则-Nacos</a>
          </li>
  • 修改resources\app\scripts\app.js
    在这里插入图片描述
      .state('dashboard.system2', {
        templateUrl: 'app/views/system_v2.html',
        url: '/v2/system/:app',
        controller: 'SystemCtl2',
        resolve: {
          loadMyFiles: ['$ocLazyLoad', function ($ocLazyLoad) {
            return $ocLazyLoad.load({
              name: 'sentinelDashboardApp',
              files: [
                'app/scripts/controllers/system_v2.js',
              ]
            });
          }]
        }
      })

  • 修改resources\app\scripts\app.js
    在这里插入图片描述
  • 新增resources\app\views\system_v2.html
    在这里插入图片描述
<div class="row" style="margin-left: 1px; margin-top:10px; height: 50px;">
  <div class="col-md-6" style="margin-bottom: 10px;">
    <span style="font-size: 30px;font-weight: bold;">{{app}}</span>
  </div>
  <div class="col-md-6">
    <button class="btn btn-default-inverse" style="float: right; margin-right: 10px;" ng-disabled="!macInputModel" ng-click="addNewRule()">
      <i class="fa fa-plus"></i>&nbsp;&nbsp;新增系统规则</button>
  </div>
</div>

<div class="separator"></div>

<div class="container-fluid">
  <div class="row" style="margin-top: 20px; margin-bottom: 20px;">
    <div class="col-md-12">
      <div class="card">
        <div class="inputs-header">
          <span class="brand" style="font-size: 13px;">系统规则</span>
          <!--<button class="btn btn-danger" style="float: right;margin-right: 10px;height: 30px;font-size: 12px;" ng-click="disableAll()">全部禁用</button>-->
          <button class="btn btn-primary" style="float: right; margin-right: 10px; height: 30px;font-size: 12px;" ng-click="getMachineRules()">刷新</button>
          <input class="form-control witdh-200" placeholder="关键字" ng-model="searchKey">
          <div class="control-group" style="float:right;margin-right: 10px;margin-bottom: -10px;">
            <selectize id="gsInput" class="selectize-input-200" config="macsInputConfig" options="macsInputOptions" ng-model="macInputModel"
              placeholder="机器"></selectize>
          </div>
        </div>

        <!--.tools-header -->
        <div class="card-body" style="padding: 0px 0px;">
          <table class="table" style="border-left: none; border-right:none;margin-top: 10px;">
            <thead>
              <tr style="background: #F3F5F7;">
                <td style="width: 40%;">
                  阈值类型
                </td>
                <td style="width: 40%;">
                  单机阈值
                </td>
                <td style="width: 12%;">
                  操作
                </td>
              </tr>
            </thead>
            <tbody>
              <tr dir-paginate="rule in rules | filter : searchKey | itemsPerPage: rulesPageConfig.pageSize " current-page="rulesPageConfig.currentPageIndex"
                pagination-id="entriesPagination">
                <td style="word-wrap:break-word;word-break:break-all;">
                  <span ng-if="rule.highestSystemLoad >= 0">系统 load</span>
                  <span ng-if="rule.avgRt >= 0">平均 RT</span>
                  <span ng-if="rule.maxThread >= 0">并发数</span>
                  <span ng-if="rule.qps >= 0">入口 QPS</span>
                  <span ng-if="rule.highestCpuUsage >= 0">CPU 使用率</span>
                </td>
                <td style="word-wrap:break-word;word-break:break-all;">
                  <span ng-if="rule.highestSystemLoad >= 0">{{rule.highestSystemLoad}}</span>
                  <span ng-if="rule.avgRt >= 0">{{rule.avgRt}}</span>
                  <span ng-if="rule.maxThread >= 0">{{rule.maxThread}}</span>
                  <span ng-if="rule.qps >= 0">{{rule.qps}}</span>
                  <span ng-if="rule.highestCpuUsage >= 0">{{rule.highestCpuUsage}}</span>
                </td>
                <td>
                  <button class="btn btn-xs btn-default" type="button" ng-click="editRule(rule)" style="font-size: 12px; height:25px;">编辑</button>
                  <button class="btn btn-xs btn-default" type="button" ng-click="deleteRule(rule)" style="font-size: 12px; height:25px;">删除</button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <!-- .card-body -->
        <div class="pagination-footer">
          <dir-pagination-controls boundary-links="true" template-url="app/views/pagination.tpl.html" pagination-id="entriesPagination"
            on-page-change="">
          </dir-pagination-controls>
          <div class="tools" style="">
            <span>共 {{rulesPageConfig.totalCount}} 条记录, </span>
            <span>
              每页
              <input class="form-control" ng-model="rulesPageConfig.pageSize"> 条记录,
            </span>
            <span>第 {{rulesPageConfig.currentPageIndex}} / {{rulesPageConfig.totalPage}} 页</span>
          </div>
          <!-- .tools -->
        </div>
        <!-- pagination-footer -->
      </div>
      <!-- .card -->
    </div>
    <!-- .col-md-12 -->
  </div>
  <!-- -->
</div>
<!-- .container-fluid -->

  • 新增resources\app\scripts\controllers\system_v2.js
    在这里插入图片描述
var app = angular.module('sentinelDashboardApp');

app.controller('SystemCtl2', ['$scope', '$stateParams', 'SystemService2', 'ngDialog', 'MachineService',
  function ($scope, $stateParams, SystemService,
    ngDialog, MachineService) {
    //初始化
    $scope.app = $stateParams.app;
    $scope.rulesPageConfig = {
      pageSize: 10,
      currentPageIndex: 1,
      totalPage: 1,
      totalCount: 0,
    };
    $scope.macsInputConfig = {
      searchField: ['text', 'value'],
      persist: true,
      create: false,
      maxItems: 1,
      render: {
        item: function (data, escape) {
          return '<div>' + escape(data.text) + '</div>';
        }
      },
      onChange: function (value, oldValue) {
        $scope.macInputModel = value;
      }
    };

    getMachineRules();
    function getMachineRules() {
      if (!$scope.macInputModel) {
        return;
      }
      let mac = $scope.macInputModel.split(':');
      SystemService.queryMachineRules($scope.app, mac[0], mac[1]).success(
        function (data) {
          if (data.code === 0 && data.data) {
            $scope.rules = data.data;
            $.each($scope.rules, function (idx, rule) {
              if (rule.highestSystemLoad >= 0) {
                rule.grade = 0;
              } else if (rule.avgRt >= 0) {
                rule.grade = 1;
              } else if (rule.maxThread >= 0) {
                rule.grade = 2;
              } else if (rule.qps >= 0) {
                rule.grade = 3;
              } else if (rule.highestCpuUsage >= 0) {
                  rule.grade = 4;
              }
            });
            $scope.rulesPageConfig.totalCount = $scope.rules.length;
          } else {
            $scope.rules = [];
            $scope.rulesPageConfig.totalCount = 0;
          }
        });
    }

    $scope.getMachineRules = getMachineRules;
    var systemRuleDialog;
    $scope.editRule = function (rule) {
      $scope.currentRule = angular.copy(rule);
      $scope.systemRuleDialog = {
        title: '编辑系统保护规则',
        type: 'edit',
        confirmBtnText: '保存'
      };
      systemRuleDialog = ngDialog.open({
        template: '/app/views/dialog/system-rule-dialog.html',
        width: 680,
        overlay: true,
        scope: $scope
      });
    };

    $scope.addNewRule = function () {
      var mac = $scope.macInputModel.split(':');
      $scope.currentRule = {
        grade: 0,
        app: $scope.app,
        ip: mac[0],
        port: mac[1],
      };
      $scope.systemRuleDialog = {
        title: '新增系统保护规则',
        type: 'add',
        confirmBtnText: '新增'
      };
      systemRuleDialog = ngDialog.open({
        template: '/app/views/dialog/system-rule-dialog.html',
        width: 680,
        overlay: true,
        scope: $scope
      });
    };

    $scope.saveRule = function () {
      if ($scope.systemRuleDialog.type === 'add') {
        addNewRule($scope.currentRule);
      } else if ($scope.systemRuleDialog.type === 'edit') {
        saveRule($scope.currentRule, true);
      }
    };

    var confirmDialog;
    $scope.deleteRule = function (rule) {
      $scope.currentRule = rule;
      var ruleTypeDesc = '';
      var ruleTypeCount = null;
      if (rule.highestSystemLoad != -1) {
        ruleTypeDesc = 'LOAD';
        ruleTypeCount = rule.highestSystemLoad;
      } else if (rule.avgRt != -1) {
        ruleTypeDesc = 'RT';
        ruleTypeCount = rule.avgRt;
      } else if (rule.maxThread != -1) {
        ruleTypeDesc = '线程数';
        ruleTypeCount = rule.maxThread;
      } else if (rule.qps != -1) {
        ruleTypeDesc = 'QPS';
        ruleTypeCount = rule.qps;
      }else if (rule.highestCpuUsage != -1) {
          ruleTypeDesc = 'CPU 使用率';
          ruleTypeCount = rule.highestCpuUsage;
      }

      $scope.confirmDialog = {
        title: '删除系统保护规则',
        type: 'delete_rule',
        attentionTitle: '请确认是否删除如下系统保护规则',
        attention: '阈值类型: ' + ruleTypeDesc + ', 阈值: ' + ruleTypeCount,
        confirmBtnText: '删除',
      };
      confirmDialog = ngDialog.open({
        template: '/app/views/dialog/confirm-dialog.html',
        scope: $scope,
        overlay: true
      });
    };


    $scope.confirm = function () {
      if ($scope.confirmDialog.type === 'delete_rule') {
        deleteRule($scope.currentRule);
        // } else if ($scope.confirmDialog.type == 'enable_rule') {
        //     $scope.currentRule.enable = true;
        //     saveRule($scope.currentRule);
        // } else if ($scope.confirmDialog.type == 'disable_rule') {
        //     $scope.currentRule.enable = false;
        //     saveRule($scope.currentRule);
        // } else if ($scope.confirmDialog.type == 'enable_all') {
        //     enableAll($scope.app);
        // } else if ($scope.confirmDialog.type == 'disable_all') {
        //     disableAll($scope.app);
      } else {
        console.error('error');
      }
    };

    function deleteRule(rule) {
      SystemService.deleteRule(rule).success(function (data) {
        if (data.code === 0) {
          getMachineRules();
          confirmDialog.close();
        } else if (data.msg != null) {
            alert('失败:' + data.msg);
        } else {
            alert('失败:未知错误');
        }
      });
    }

    function addNewRule(rule) {
      if (rule.grade == 4 && (rule.highestCpuUsage < 0 || rule.highestCpuUsage > 1)) {
        alert('CPU 使用率模式的取值范围应为 [0.0, 1.0],对应 0% - 100%');
        return;
      }
      SystemService.newRule(rule).success(function (data) {
        if (data.code === 0) {
          getMachineRules();
          systemRuleDialog.close();
        } else if (data.msg != null) {
          alert('失败:' + data.msg);
        } else {
          alert('失败:未知错误');
        }
      });
    }

    function saveRule(rule, edit) {
      SystemService.saveRule(rule).success(function (data) {
        if (data.code === 0) {
          getMachineRules();
          if (edit) {
            systemRuleDialog.close();
          } else {
            confirmDialog.close();
          }
        } else if (data.msg != null) {
          alert('失败:' + data.msg);
        } else {
          alert('失败:未知错误');
        }
      });
    }
    queryAppMachines();
    function queryAppMachines() {
      MachineService.getAppMachines($scope.app).success(
        function (data) {
          if (data.code === 0) {
            // $scope.machines = data.data;
            if (data.data) {
              $scope.machines = [];
              $scope.macsInputOptions = [];
              data.data.forEach(function (item) {
                if (item.healthy) {
                  $scope.macsInputOptions.push({
                    text: item.ip + ':' + item.port,
                    value: item.ip + ':' + item.port
                  });
                }
              });
            }
            if ($scope.macsInputOptions.length > 0) {
              $scope.macInputModel = $scope.macsInputOptions[0].value;
            }
          } else {
            $scope.macsInputOptions = [];
          }
        }
      );
    };
    $scope.$watch('macInputModel', function () {
      if ($scope.macInputModel) {
        getMachineRules();
      }
    });
  }]);

  • 新增resources\app\scripts\services\systemservice_v2.js
    在这里插入图片描述
var app = angular.module('sentinelDashboardApp');

app.service('SystemService2', ['$http', function ($http) {
  this.queryMachineRules = function (app, ip, port) {
    var param = {
      app: app,
      ip: ip,
      port: port
    };
    return $http({
      url: '/v2/system/rules.json',
      params: param,
      method: 'GET'
    });
  };

  this.newRule = function (rule) {
    var param = {
      app: rule.app,
      ip: rule.ip,
      port: rule.port
    };
    if (rule.grade == 0) {// avgLoad
      param.highestSystemLoad = rule.highestSystemLoad;
    } else if (rule.grade == 1) {// avgRt
      param.avgRt = rule.avgRt;
    } else if (rule.grade == 2) {// maxThread
      param.maxThread = rule.maxThread;
    } else if (rule.grade == 3) {// qps
      param.qps = rule.qps;
    } else if (rule.grade == 4) {// cpu
      param.highestCpuUsage = rule.highestCpuUsage;
    }

    return $http({
      url: '/v2/system/new.json',
      params: param,
      method: 'GET'
    });
  };

  this.saveRule = function (rule) {
    var param = {
      id: rule.id,
    };
    if (rule.grade == 0) {// avgLoad
      param.highestSystemLoad = rule.highestSystemLoad;
    } else if (rule.grade == 1) {// avgRt
      param.avgRt = rule.avgRt;
    } else if (rule.grade == 2) {// maxThread
      param.maxThread = rule.maxThread;
    } else if (rule.grade == 3) {// qps
      param.qps = rule.qps;
    } else if (rule.grade == 4) {// cpu
        param.highestCpuUsage = rule.highestCpuUsage;
    }

    return $http({
      url: '/v2/system/save.json',
      params: param,
      method: 'GET'
    });
  };

  this.deleteRule = function (rule) {
    var param = {
      id: rule.id,
      app: rule.app
    };

    return $http({
      url: '/v2/system/delete.json',
      params: param,
      method: 'GET'
    });
  };
}]);

  • 修改resources\dist\js\app.js
    在这里插入图片描述
, (app = angular.module("sentinelDashboardApp")).service("SystemService2", ["$http", function (a) {
    this.queryMachineRules = function (e, t, r) {
        return a({url: "/v2/system/rules.json", params: {app: e, ip: t, port: r}, method: "GET"})
    }, this.newRule = function (e) {
        var t = {app: e.app, ip: e.ip, port: e.port};
        return 0 == e.grade ? t.highestSystemLoad = e.highestSystemLoad : 1 == e.grade ? t.avgRt = e.avgRt : 2 == e.grade ? t.maxThread = e.maxThread : 3 == e.grade ? t.qps = e.qps : 4 == e.grade && (t.highestCpuUsage = e.highestCpuUsage), a({
            url: "/v2/system/new.json",
            params: t,
            method: "GET"
        })
    }, this.saveRule = function (e) {
        var t = {id: e.id};
        return 0 == e.grade ? t.highestSystemLoad = e.highestSystemLoad : 1 == e.grade ? t.avgRt = e.avgRt : 2 == e.grade ? t.maxThread = e.maxThread : 3 == e.grade ? t.qps = e.qps : 4 == e.grade && (t.highestCpuUsage = e.highestCpuUsage), a({
            url: "/v2/system/save.json",
            params: t,
            method: "GET"
        })
    }, this.deleteRule = function (e) {
        var t = {id: e.id, app: e.app};
        return a({url: "/v2/system/delete.json", params: t, method: "GET"})
    }
}])
  • 修改resources\gulpfile.js

在这里插入图片描述

'app/scripts/services/systemservice_v2.js',
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值