用Netscaler的Variable和Assignment來實現計數控制
Variable變量和Assignment調度的手冊:
https://docs.citrix.com/en-us/netscaler/11-1/appexpert/variables.html
在負載均衡做各種複雜策略的時候往往會碰到需要前後有連續性的狀態計數,netscaler作爲一個策略封裝比較友好的ADC在提供完善策略安全性保障的同時還提供了比較開放的編程環境。在編程中很關鍵的一環就是變量的定義和使用,我們就變量這一話題來看netscaler能夠提供怎樣的功能。本文拋磚引玉爲目的,提供一個思路供大家參考,具體應用場景還需要大家發散性思考。
定義變量
長整型: ------------------------------- 數組型:
add ns variable name_variable -type ulong -init 1 -expires 3600
add ns variable my_variable -type "map(text(20),ulong,500)" -init 15 -expires 600
調用變量進行計算
進行計算的方式有如下:add加法、set重設成某個值、sub減法、append附加、clear清除
add ns assignment name_assign_add -variable "$name_variable" -add 1
add ns assignment my_assign -variable "$my_variable[HTTP.REQ.HEADER(\"CJ_Cookie\")]" -add 1
計算好的變量Variable可以在Policy裏當Action使用,或者在表達式中來做判斷依據
調用的方法如下:$variable_name.valueExists.其他表達式(返回布爾值)或$variable_name.valueCount.其他表達式(返回數值)
$name.valueExists(key-expression). Returns true if there is a value in the map selected by the key-expression. Otherwise returns false. This function will update the expiration and LRU information if the map entry exists, but will not create a new map entry if the value does not exist.
$name.valueCount. Returns the number of values currently held by the variable. This is the number of entries in a map. For a singleton variable, this is 0 if the variable is uninitialized or 1 otherwise.
例如:
$name_variable.GE(10);
$my_variable.valueCount.EQ(10)
add rewrite action rw_action_variable_waring2 insert_after_all "HTTP.RES.BODY(59999).SET_TEXT_MODE(IGNORECASE)" "\"this is waring\"" -pattern "隨波漢化版"
add rewrite policy rw_policy_variable_waring "$name_variable.GE(10)" rw_action_variable_waring2
實現效果:當變量大於10的時候執行插入body的動作
或着在action中定義插入一個cookie值,名字爲CJ_Count: 值爲變量的值
add rewrite action rw_action_variable insert_http_header Set-Cookie "\"CJ_Count:\"+$name_variable"
測試案例use case:
定義變量,做爲計數用戶訪問或登錄次數
add ns variable name_variable -type ulong -init 1 -expires 3600
add ns variable name_variable_dele -type ulong -init 1 -expires 3600
調用兩個變量並計算:
name_assign_add 每次增加1 ------------------ name_assign_dele 每次把變量清除
add ns assignment name_assign_add -variable "$name_variable" -add 1
add ns assignment name_assign_dele -variable "$name_variable" -clear
Rewrite策略:
rewrite策略實現訪問URL=03時,variable增加1,訪問URL=callout時,variable清除;請求header中Accetp爲text時插入COOKIE
add rewrite policy rw_policy_variable "HTTP.REQ.HEADER(\"Accept\").CONTAINS(\"text\")" rw_action_variable
add rewrite policy rw_policy_variable_add "HTTP.REQ.URL.PATH.GET(1).EQ(\"03\")" name_assign_add
add rewrite policy rw_policy_variable_dele "HTTP.REQ.URL.PATH.GET(1).EQ(\"callout\")" name_assign_dele
action爲:插入cookie,名字爲CJ_Count,值爲變量的值
add rewrite action rw_action_variable insert_http_header Set-Cookie "\"CJ_Count:\"+$name_variable"
效果:
登錄主頁時,由於accept爲text,遂插入cookie:CJ_Cookie=1
每次訪問URL=/03時Cookie的值+1
訪問URL=/callout時,把cookie的值清除