就算你年薪二十萬,教授也只推薦買這些十多萬的車

對不起,真正為玩車的人是玩手動擋的不喜歡日系車。那高爾夫R-Line也是能讓你爽翻的車重只有1。3噸的R-Line卻有着150ps的馬力搭配換擋奇快的7速雙離合秒殺BBA不是夢當然,也有人買車不是為了玩對於顧家好男人來說空間太小,就算車子會飛也沒有用那這個時候,擁有寬裕後排的B級車就是你的首選什麼。

老K是的一位朋友

他是某保險公司的高級銷售

相當的敬業

所謂一分耕耘一分收穫

兢兢業業的老K現在已經是年薪二十萬的有錢淫

收入比叫獸高好幾個檔次呢

有錢了,逼格肯定要跟上

老K立馬去4S給提了一輛BBA

然而

讓老K意想不到的是

養一輛豪車比他想象的吃力

油耗和保險已經夠厲害了

維修保養就更別說

進去一次4S店

坑你個三五千都是洒洒碎

所以老K很後悔當初沒有聽叫獸的話

買一輛十來萬的車

然而這已經太遲了

為了避免大家重走老K的路

叫獸有必要說說

哪怕你年薪二十萬,買一輛十來萬的車就夠了

十來萬的車子其實也可以很有逼格

雖然太愛面子不是好事

但是一個人開什麼車子的確體現了他的品味

就像老K的BBA,起碼在外人看來不是垃圾

然而你真要高逼格的話,十來萬的車確實也有

記得第一次看見博瑞實車的時候

還以為是哪個品牌的新款進口車

走進一看才發現這是大名鼎鼎的博瑞

連都會產生這種錯覺

那對於不太懂車的人來說

博瑞的逼格就不言而喻了

那假如想要強勁的動力呢?

思域神車就能給到本站聲明:網站內容來源於http://www.auto6s.com/,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

※別再煩惱如何寫文案,掌握八大原則!

※網頁設計一頭霧水該從何著手呢? 台北網頁設計公司幫您輕鬆架站!

※超省錢租車方案

※教你寫出一流的銷售文案?

※網頁設計最專業,超強功能平台可客製化

※產品缺大量曝光嗎?你需要的是一流包裝設計!

合資SUV都被國產車逼的跌破10萬了…現在是入手的好時機!

為了打破這種障礙,KX3改款之後變得圓潤了很多。作為改款車型,KX3的外觀造型變化不大。主要把前臉LED日間行車燈的位置往下移了之後,變得更加的協調可愛。圓潤的前臉配合大嘴的設計,很具特色。飽滿的車身線條流暢自然。

合資小型SUV雖然價格相對於自主SUV車型而言,總體的價格真的高了不少。雖則價格高那麼多,但總每一個月的銷量來看合資小型SUV確是不低。歸根到底既是合資SUV的顏值很高,而且它質量相對更加可靠也是很多消費者看重的地方。但消費者買車肯定想着能省一分是一分的,最近看到目前很火的幾款小型SUV市場上的終端優惠不低,不知道你看到之後有沒有想買車的想法呢?

大家都能看到,這幾款車型的起步價大多數在10萬以下,很好地切入合資緊湊SUV的區間。對於定價不算很高,因此1萬多的優惠將相當具有吸引力了。

上汽通用雪佛蘭 創酷

售價:9.99-14.99萬元

作為合資小型SUV的先行者,創酷雖然不算很熱,但銷量一直都不錯,但受限於之前沒有改款,顏值有些落後與對手,使得整體熱度有所降低。如今新款更加出色的造型與較低的售價使得性價比很高。

全新創酷採用家族式造型設計變得更加的年輕時尚,分體格柵的造型使得前臉更具立體感。U型LED日間行車燈造型犀利,視覺效果出眾。飽滿車身造型與立體感很強的車尾造型很出色;輪眉凸起的線條多了一些硬派氣息。

相比老款,新款創酷的內飾實在是太時尚了;環繞式中控台黑棕的配色顯得大膽活潑;高配車型多媒體區域還有7英寸大屏,鋼琴烤漆工藝質感十足。相比它的外觀與內飾變化很大,由於是改款車型,它的空間仍然表現一般,勉強夠用。

創酷全系搭載的是一台1.4T發動機,143ps表現非常出色。日常使用與6AT變速箱搭配良好,換擋邏輯做得不錯。懸挂的韌性相當出色,但卻不會做得太硬影響舒適性。當然缺點還有有點,低速時換擋會有點頓挫。

北京現代 ix25

售價:11.98-18.68萬元

ix25作為現代最小型的SUV車型,它主打的仍是它時尚亮眼的外觀造型,同時還有比同級SUV較大的身材與超過的性價比。而且如今市場上也有不少優惠,屬於比較值得購買的一款SUV車型。

ix25的外觀整體感很出色,雖說第一眼不算很驚艷。但採用流體雕塑感念的前臉還是相當耐看的,多邊形的進氣格柵採用橫向鍍鉻條,質感十足。微微上揚的腰線配合懸浮式車頂造型整體呈現很硬朗陽剛。車尾則設計得比較飽滿敦實,卻不會太過張揚。

ix25的內飾造型則相對平淡一些,規整的中控台採用飛翼式設計,呈現簡潔的氣息。灰黑色的內飾搭配總體比較順眼,總的來說它的比較出色的就是均衡的空間與豐富的配置了。

ix25的動力總成非常豐富,能滿足不同消費者的需求。走量的1.6L車型125ps輸出中規中矩,日常代步足夠了。總的來說2.0L的車型會更好一些;6AT變速箱在平時行駛時換擋也相當出色。更高的1.6T車型動力是不錯,但性價比差了點。總的來說,ix25轉向輕盈,底盤舒適,是一台很好開的小型SUV。

東風悅達起亞 KX3

售價:11.28-17.78萬元

起亞相比現代而已,它們的風格不太相似。起亞的外觀設計更加激進一些,比較符合年輕人,但這樣受眾就比較窄了。為了打破這種障礙,KX3改款之後變得圓潤了很多。

作為改款車型,KX3的外觀造型變化不大。主要把前臉LED日間行車燈的位置往下移了之後,變得更加的協調可愛。圓潤的前臉配合大嘴的設計,很具特色。飽滿的車身線條流暢自然。車尾則採用簡潔的設計,耐看美觀。

全新KX3的內飾變化不大,設計感十足的內飾造型很有特色。層次感很強的中控台採用鋼琴烤漆工藝與紅色裝飾點綴,很吸人眼球。而且它的配置也空間都比較出色,很適合那些對配置比較注重的消費者。

全新KX3隻搭載了1.6L/1.6T發動機,2.0L車型不再推出。1.6L車型動力輸出一般,整體來說畢竟輕盈;對於日常代步的消費者已經足夠了。1.6T發動機動力更直接一些,而且這套雙離合變速箱做得相當出色,能媲美大眾的雙離合了。偏沉的懸挂需要適應一下,懸挂的調校則以家用舒適為目的。

上汽通用別克 昂科拉

售價:13.99-18.99萬元

昂科拉也迎來了改款,作為跟創酷差不多時間進入國內的小型SUV車型。當時市場空白,它可謂是佔了先機,但由於改款腳步較慢,性價比一般使得它銷量降低了不少。

新款昂科拉的外觀造型終於跟上潮流的,變得更加時尚年輕的造型很吸引年輕人。全新的家族式造型設計與別克其他車型有了延續,飽滿的前臉與鍍鉻裝飾檔次感十足。微微隆起的輪轂線條也使得它多了一些野性。車尾採用了新式樣的尾燈,視覺效果更出色。

作為比創酷高一個檔次的車型,昂科拉的內飾質感很強。簡潔的內飾造型是別克最新的家族式造型設計,很時尚年輕。而且厚道的用料與出色的做工也在細節上一一體現,唯一的弱點就是後排空間比較一般。

新款昂科拉也是全系搭載的是一台1.4T發動機,動力與創酷相差不大。而且也沒有採用雙離合變速箱,6AT保證了日常使用的平順性。1.4T動力出色,起步相當輕鬆。懸挂支撐性很高,具有較高的穩定性。但較硬的懸挂帶來的不好的影響就是舒適性一般,而且高速噪音偏高。

作為時下最火熱的幾款小型SUV車型,今天所推薦的這幾款價格有高有低。創酷自從改款之後,外觀造型終於不落後於競爭對手了;而且不到10萬的價格如今再加上優惠性價比很出眾。ix25則是一款實力比較均衡的車型,流體雕塑感念造型很出色;豐富的配置與寬敞的空間也是一大亮點。

起亞的KX3與ix25是兩種不同的路,它更加講求個性;老款太激進使得受眾較窄;新款變得笑容可掬與消費者更親近了。而且它降低的售價與豐富的配置也是它吸引年輕人的優勢。最後的昂科拉,雖則價格相對高一些,但它出色的外觀造型與檔次感很高的內飾質感都是它的底氣,如今加上優惠就更值得入手了。本站聲明:網站內容來源於http://www.auto6s.com/,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

※教你寫出一流的銷售文案?

※廣告預算用在刀口上,台北網頁設計公司幫您達到更多曝光效益

※回頭車貨運收費標準

※別再煩惱如何寫文案,掌握八大原則!

※超省錢租車方案

※產品缺大量曝光嗎?你需要的是一流包裝設計!

這些事情SUV可以輕鬆做到,轎車完全不行

、所說SUV有着以上優點,但是上下車對老人不友好以及盲區大、油耗大這些缺點還是存在的,關鍵還是根據自身需求出發選擇SUV還是轎車。

、

所說SUV有着以上優點,但是上下車對老人不友好以及盲區大、油耗大這些缺點還是存在的,關鍵還是根據自身需求出發選擇SUV還是轎車。本站聲明:網站內容來源於http://www.auto6s.com/,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

※超省錢租車方案

※別再煩惱如何寫文案,掌握八大原則!

※回頭車貨運收費標準

※教你寫出一流的銷售文案?

※產品缺大量曝光嗎?你需要的是一流包裝設計!

※廣告預算用在刀口上,台北網頁設計公司幫您達到更多曝光效益

Redis 持久化

RDB

簡介

RDB持久化方式是通過快照(snapshotting)完成的,當符合一定條件時,redis會自動將內存中所有數據以二進制方式生成一份副本並存儲在硬盤上。當redis重啟時,並且AOF持久化未開啟時,redis會讀取RDB持久化生成的二進制文件(默認名稱dump.rdb,可通過設置dbfilename修改)進行數據恢復,對於持久化信息可以用過命令“info Persistence”查看。

save

該命令會由worker thread 執行,因此會阻塞 redis 的 worker ,期間不會響應任何其他客戶端發來的請求,直到RDB快照文件執行完畢,所以慎用。

測試

info persistence 
# rdb_last_save_time:1570126868
save
info persistence
# rdb_last_save_time:1570126928

bgsave

bgsave“後台保存”。與save 最大的差異為它並不是由 worker thread 執行的,而是由redis fork 齣子進程,交由子進程來完成持久化操作。

redis在fork子進程這個時間段內 redis是阻塞的(此段時間不會響應客戶端請求),當子進程創建完成以後redis才會響應客戶端請求。

並且redis不會在控制台显示完成信息,只會寫入日誌。

流程

客戶端執行bgsave命令,redis主進程收到指令並判斷此時是否在執行bgrewriteaof(AOF文件重新過程,後續會講解),如果此時正好在執行則bgsave直接返回,不fork子進程,如果沒有執行bgrewriteaof重寫AOF文件,則進入下一個階段;

主進程調用fork方法創建子進程,在創建子進程過程中redis主進程阻塞,所以不能響應客戶端請求;

子進程創建完成以後,bgsave命令返回Background saving started,此時標志著redis可以響應客戶端請求了;

子經常根據主進程的內存副本創建臨時快照文件,當快照文件完成以後對原快照文件進行替換;

子進程發送信號給redis主進程完成快照操作,主進程更新統計信息(info Persistence可查看),子進程退出;

測試

bgsave
Background saving started  # 子進程創建成功,它會去 完成持久化操作

查看日誌

config get logfile
 11) "logfile"
 12) "/var/log/redis/redis-server.log"
cat "/var/log/redis/redis-server.log"
2497:M 04 Oct 2019 10:26:46.764 * Background saving started by pid 28960   # 開始後台 持久化
2497:M 04 Oct 2020 10:26:46.772 * Background saving terminated with success   # 後台持久化完成 

RDB相關配置

查看配置的方法:

1 查看配置文件

2 在redis 中查看當前 redis 的配置

CONFIG get *    # 獲取所有的配置
CONFIG get dir   # 獲取 快照文件 保存的 位置
CONFIG get dbfilename   # 獲取 快照文件 的文件名

快照文件位置

配置文件中 dir 指定

快照文件名

配置文件中 dbfilename

是否壓縮

配置文件中 rdbcompression default:yes

設置存儲至本地數據庫時是否壓縮數據,默認為yes,採用LZF壓縮

yes 會耗費一定的CPU資源,默認是 yes 。

no 會使存儲的文件變大(巨大)

是否校驗

配置文件中 yesrdbchecksumy default: yes

yes 會消耗一部分CPU資源,但是數據相對安全不容易損壞

no 可以節約讀寫性過程約10%時間消耗,但是存儲一定的數據損壞風險

後台持久化報錯

配置文件中 stop-writes-on-bgsave-error default: yes

後台存儲過程中如果出現錯誤線程,是否停止保存操作,默認是停止的

no 則忽略錯誤繼續。

快照檢查

配置文件中 rdbchecksum default: yes
在寫入文件和讀取文件時是否開啟rdb文件檢查,檢查是否有無損壞,如果在啟動是檢查發現損壞,則停止啟動。

RDB觸發

自動觸發

配置文件中 save default: yes

save second changes
# 查看默認的配置
config get save
"900 1 300 10 60 10000"
# 900秒內 1次鍵更新了就觸發持久化 或 300秒內 10次更新 持久化 60 秒內 10000次更新 觸發持久化
# 該持久化是 bgsave

手動觸發

手動執行 save 或 bgsave

其他觸發

以下幾種種情況下會觸發執行快照操作,並且默認的使用bgsave

主從複製時,從庫全量複製同步主庫數據,此時主庫會執行bgsave命令進行快照;

客戶端執行數據庫清空命令FLUSHALL時候,觸發快照;

客戶端執行shutdown關閉redis時,觸發快照,也可以 使用 nosave 參數顯式聲明不保存快照

shutdown nosave

故障恢復

當redis意外崩潰或者關閉再次啟動時,此時AOF持久化未開啟時(默認未開啟),將使用RDB快照文件恢複數據。

# 查看日誌
cat /var/log/redis/redis-server.log
30448:M 04 Oct 2019 10:09:37.145 # Server initialized
30448:M 04 Oct 2019 10:09:37.145 * DB loaded from disk: 0.000 seconds   # 從快照恢復
30448:M 04 Oct 2019 10:09:37.146 * Ready to accept connections

缺點

RDB方式無論是執行指令還是利用配置,無法做到實時持久化,具體較大的可能性丟失數據

bgsave指令每次運行要執行fork操作創建子進程,要犧牲掉一些性能

Redis的眾多版本中未進行RDB文件格式的版本統一,有可能出現個版本服務之間數據格式無法兼容現象

存儲數據量較大,效率較低——基於快照思想,每次讀寫都是全部數據,當數據量巨大時,效率非常低
大數據量下的IO性能較低

AOF

簡介

日誌形式的AOF,將命令追加到文件。AOF可以將Redis執行的每一條寫命令追加到磁盤文件(appendonly.aof)中,在redis啟動時候優先選擇從AOF文件恢複數據。因為要頻繁的將每一個操作記錄到文件中,所以開啟AOF持久化會對性能有一定的影響,但是大部分情況下這個影響是可以接受的。

與RDB持久化相比,AOF持久化數據丟失更少,其消耗內存更少(RDB方式執行bgsve會有內存拷貝)。

AOF持久化過程

redisAOF持久化過程可分為以下階段:

追加寫入

redis將每一條寫命令以redis通訊協議添加至緩衝區aof_buf,這樣的好處在於在大量寫請求情況下,採用緩衝區暫存一部分命令隨後根據策略一次性寫入磁盤,這樣可以減少磁盤的I/O次數,提高性能。

同步三種策略

當寫命令寫入aof_buf緩衝區后,redis會將緩衝區的命令寫入到文件,redis提供了三種同步策略,由配置參數appendfsync決定,下面是每個策略所對應的含義:

no

不使用fsync方法同步,而是交給操作系統write函數去執行同步操作,在linux操作系統中大約每30秒執行一次 sync(man 2 sync 查看)。這種情況下,緩衝區數據同步不可控,並且在大量的寫操作下,aof_buf緩衝區會堆積會越來越嚴重,一旦redis出現故障,數據丟失嚴重,整體不可控。

always

表示每次有寫操作都調用fsync方法強制內核將數據寫入到aof文件。這種情況下由於每次寫命令都寫到了文件中, 雖然數據比較安全,但是因為每次寫操作都會同步到AOF文件中,所以在性能上會有影響,同時由於頻繁的IO操作,硬盤的使用壽命會降低。

everysec

數據將使用調用操作系統write寫入文件,並使用fsync每秒一次從內核刷新到磁盤。 這是折中的方案,兼顧性能和數據安全,所以redis默認推薦使用該配置。

文件重寫

當開啟AOF時,隨着時間推移,AOF文件會越來越大,redis提出一種重寫的策略來緩解數據存儲和恢復壓力。

重寫策略

重複或無效的命令不寫入文件

過期的數據不再寫入文件

多條命令合併寫入(當多個命令能合併一條命令時候會對其優化合併作為一個命令寫入,例如“RPUSH list1 a RPUSH list1 b” 合併為“RPUSH list1 a b” )

觸發條件

AOF文件觸發條件可分為手動觸發和自動觸發:

手動觸發:客戶端執行bgrewriteaof命令。

自動觸發:自動觸發通過以下兩個配置協作生效:

auto-aof-rewrite-min-size

AOF文件最小重寫大小,只有當AOF文件大小大於該值時候才可能重寫,4.0默認配置64mb。

auto-aof-rewrite-percentage

當前AOF文件大小和最後一次重寫后的大小之間的比率等於或者等於指定的增長百分比,如100代表當前AOF文件是上次重寫的兩倍時候才重寫。 

redis在AOF功能開啟的情況下,會維持以下三個變量

aof_current_size :記錄當前AOF文件大小

aof_rewrite_base_size:記錄最後一次AOF重寫之後,AOF文件大小

aof_rewrite_perc:增長百分比變量

每次當serverCron(服務器周期性操作函數)函數執行時,它會檢查以下條件是否全部滿足,如果全部滿足的話,就觸發自動的AOF重寫操作:

沒有BGSAVE命令(RDB持久化)/AOF持久化在執行;

沒有BGREWRITEAOF在進行;

當前AOF文件大小要大於server.aof_rewrite_min_size的值;

當前AOF文件大小和最後一次重寫后的大小之間的比率等於或者大於指定的增長百分比(auto-aof-rewrite-percentage參數)

重寫過程

  AOF文件重寫過程與RDB快照bgsave工作過程有點相似,都是通過fork子進程,由子進程完成相應的操作,同樣的在fork子進程簡短的時間內,redis是阻塞的,以下圖文說明其重寫過程:

開始bgrewriteaof,判斷當前有沒有bgsave命令(RDB持久化)/bgrewriteaof在執行,倘若有,則這些命令執行完成以後在執行。

主進程fork齣子進程,在這一個短暫的時間內,redis是阻塞的。

當完成重寫后,將重寫后的aof 文件合併到原有aof緩存文件中。並刪除臨時創建的重寫后的aof文件

AOF實現本質

AOF實現本質是基於redis通訊協議,將命令以純文本的方式寫入到文件中。

redis協議:

首先Redis是以行來劃分,每行以\r\n行結束。每一行都有一個消息頭,消息頭共分為5種分別如下:

(+) 表示一個正確的狀態信息,具體信息是當前行+後面的字符。

(-) 表示一個錯誤信息,具體信息是當前行-後面的字符。

(*) 表示消息體總共有多少行,不包括當前行,*後面是具體的行數。

($) 表示下一行數據長度,不包括換行符長度\r\n,$後面則是對應的長度的數據。

(:) 表示返回一個數值,:後面是相應的数字節符。

我們可以直接查看AOF文件中的格式,如下圖:

數據恢復

之前已經提到當AOF開啟時候,redis數據恢復優先選用AOF進行數據恢復,以下使用停止redis來模擬redis故障,然後在重寫啟動進行恢復。

AOF配置參數

auto-aof-rewrite-min-size

AOF文件最小重寫大小,只有當AOF文件大小大於該值時候才可能重寫,4.0默認配置64mb。

auto-aof-rewrite-percentage

當前AOF文件大小和最後一次重寫后的大小之間的比率等於或者等於指定的增長百分比,如100代表當前AOF文件是上次重寫的兩倍時候才重寫。默認 100

appendfsync

上文中提到的三種策略,默認 everysec

always | everysec | no

aof-load-truncated yes

當redis突然運行崩潰時,會出現aof文件被截斷的情況,Redis可以在發生這種情況時退出並加載錯誤,以下選項控制此行為。
如果aof-load-truncated設置為yes,則加載截斷的AOF文件,Redis服務器啟動發出日誌以通知用戶該事件。
如果該選項設置為no,則服務將中止並显示錯誤並停止啟動。當該選項設置為no時,用戶需要在重啟之前使用redis-check-aof實用程序修復AOF文件在進行啟動。

appendonly no

yes開啟AOF,no關閉AOF 默認 no

appendfilename

指定AOF文件名,4.0無法通過config set 設置,只能通過修改配置文件設置。默認 appendonly.aof

RDB-AOF混合持久化

簡介

redis4.0添加了新的持久化方式混合持久化。

混合持久化默認是關閉的,它採用一種rdb + aof 的方式來實現,文件頭rdb 一個全量的快照,格式為二進制,後面是 aof 格式。這樣恢復會先查看開頭是否為REDIS,rdb開頭必然是REDIS。然後從快照恢復,之後從aof恢復。

這樣做的好處是可以結合 rdb 和 aof 的優點, 快速加載同時避免丟失過多的數據

缺點是 aof 裏面的 rdb 部分就是壓縮格式不再是 aof 格式,可讀性差。

開啟混合持久化

5 版本的redis 默認的開啟了aof-use-rdb-preamble 但是 appendonly 默認是 no 也就是說,只要開啟了aof 默認的會使用混合持久化。如果要使用單純的aof 則需要手動的 將 aof-use-rdb-preamble 設為 no (好坑)

4.0版本的混合持久化默認關閉的,通過aof-use-rdb-preamble配置參數控制,yes則表示開啟,no表示禁用,默認是禁用的,可通過config set修改。

混合持久化過程

創建子進程

生成全量的rdb快照,放在appendonly.aof 文件頭部。然後,接下來將aof緩衝區的增量命令以aof方式寫入文件尾

每次恢複數據時,首先從RDB部分恢復,然後執行aof。

數據恢復

開啟了混合持久化時,啟動redis依然優先加載aof文件,aof文件加載可能有兩種情況如下:

aof文件開頭是rdb的格式, 先加載 rdb內容再加載剩餘的 aof。

aof文件開頭不是rdb的格式,直接以aof格式加載整個文件。

三種持久化方案對比

RDB

優點

RDB 是一個非常緊湊(compact)的文件,體積小,傳輸速度快,適合災備。

RDB 可以最大化 Redis 的性能:父進程在保存 RDB 文件時唯一要做的就是 fork 出一個子進程,然後這個子進程就會處理接下來的所有保存工作,父進程無須執行任何磁盤 I/O 操作。

RDB 在恢復大數據集時的速度比 AOF 的恢復速度要快很多。

缺點

RDB 丟數據將會丟掉兩次持久化之間的所有數據~

當redis中數據集比較大時候,RDB由於RDB方式需要對數據進行完成拷貝並生成快照文件,fork的子進程會耗CPU,並且數據越大,RDB快照生成會越耗時。

RDB文件是特定的格式,閱讀性差,由於格式固定,並且多版本之間存在不兼容情況。很難受~

AOF

優點

數據更完整,秒級數據丟失(取決於設置fsync策略)

兼容性較高,由於是基於redis通訊協議而形成的命令追加方式,無論何種版本的redis都兼容,再者aof文件是明文的,可閱讀性較好。

缺點

數據文件體積較大,即使有重寫機制,但是在相同的數據集情況下,AOF文件通常比RDB文件大。

相對RDB方式,AOF速度慢於RDB,並且在數據量大時候,恢復速度AOF速度也是慢於RDB。

由於頻繁地將命令同步到文件中,AOF持久化對性能的影響相對RDB較大,但是對於我們來說是可以接受的。

混合持久化

優點

混合持久化結合了RDB持久化 和 AOF 持久化的優點, 由於絕大部分都是RDB格式,加載速度快,同時結合AOF,增量的數據以AOF方式保存了,數據更少的丟失。

缺點

由於前部分是RDB格式,閱讀性較差,兼容性差,一旦開啟了混合持久化,4.0 版本之前的redis 都不認識這種aof文件~ 。

本站聲明:網站內容來源於博客園,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

※為什麼 USB CONNECTOR 是電子產業重要的元件?

※網頁設計一頭霧水該從何著手呢? 台北網頁設計公司幫您輕鬆架站!

※台北網頁設計公司全省服務真心推薦

※想知道最厲害的網頁設計公司"嚨底家"!

※推薦評價好的iphone維修中心

@Autowired 註解詳解

前言

我們平時使用 Spring 時,想要 依賴注入 時使用最多的是 @Autowired 註解了,本文主要講解 Spring 是如何處理該註解並實現 依賴注入 的功能的。

正文

首先我們看一個測試用例:

User 實體類:

public class User {

    private Long id;
    private String name;

	// 省略 get 和 set 方法
}

測試類:

public class AnnotationDependencyInjectTest {

    /**
     * @Autowired 字段注入
     */
    @Autowired
    private User user;

    private City city;

    /**
     * @Autowired 方法注入
     */
    @Autowired
    public void initCity(City city) {
        this.city = city;
    }

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.register(AnnotationDependencyInjectTest.class);
        context.refresh();
        AnnotationDependencyInjectTest bean = context.getBean(AnnotationDependencyInjectTest.class);
        // @Autowired 字段注入
        System.out.println(bean.user);
        // @Autowired 方法注入
        System.out.println(bean.city);
        UserHolder userHolder = context.getBean(UserHolder.class);
        // @Autowired 構造器注入
        System.out.println(userHolder.getUser());
        context.close();
    }

    @Bean
    public User user() {
        User user = new User();
        user.setId(1L);
        user.setName("leisurexi");
        return user;
    }

    @Bean
    public City city() {
        City city = new City();
        city.setId(1L);
        city.setName("北京");
        return city;
    }
    
    /**
     * @Autowired 構造函數注入
     */
    static class UserHolder {

        private User user;

        @Autowired
        public UserHolder(User user) {
            this.user = user;
        }

        public User getUser() {
            return user;
        }

        public void setUser(User user) {
            this.user = user;
        }
    }

}

上面分別展示了 @Autowired 註解的字段注入和方法注入,下面我們開始分析 Spring 是如何實現的。

首先使 @Autowired 註解生效的一個關鍵類是 AutowiredAnnotationBeanPostProcessor,該類實現了 InstantiationAwareBeanPostProcessorAdapter 抽象類;該抽象類就是一個適配器的作用提供了接口方法的默認實現,InstantiationAwareBeanPostProcessorAdapter 又實現了 SmartInstantiationAwareBeanPostProcessor 接口,同時實現該接口的 determineCandidateConstructors() 方法可以指定 bean 的候選構造函數;然後 SmartInstantiationAwareBeanPostProcessor 接口又繼承了 InstantiationAwareBeanPostProcessor 接口,該接口提供了 bean 實例化前後的生命周期回調以及屬性賦值前的後置處理方法,@Autowired 註解的屬性注入就是通過重寫該接口的 postProcessProperties() 實現的。這兩個接口都在 在 Spring IoC createBean 方法詳解 一文中有介紹過。下面我們看一下 AutowiredAnnotationBeanProcessor 的繼承關係圖:

關於 AutowiredAnnotationBeanPostProcessor 這個後置處理器是怎麼加入到 beanFactory 中的,我們在 Spring IoC component-scan 節點詳解 一文中介紹過主要是通過 AnnotationConfigUtils#registerAnnotationConfigProcessors() 實現的。

public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
    BeanDefinitionRegistry registry, @Nullable Object source) {
    
    // 忽略其它代碼
    
    // 註冊用於處理@Autowired、@Value、@Inject註解的後置處理器
    if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
        RootBeanDefinition def = new
            RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
        def.setSource(source);
        beanDefs.add(registerPostProcessor(registry, def,
                                           AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
    }
    // 忽略其它代碼
    
}

屬性和方法注入

AutowiredAnnotationBeanPostProcessor 中跟屬性注入有關的方法有兩個:postProcessMergedBeanDefinition 和 postProcessPropertyValues。

前者是 MergedBeanDefinitionPostProcessor 接口中的方法,定義如下:

public interface MergedBeanDefinitionPostProcessor extends BeanPostProcessor {

	/**
	 * 對指定bean的BeanDefinition合併后的處理方法回調
	 */
	void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName);

	/**
	 * @since 5.1
	 * 通知已重新設置指定beanName的BeanDefinition,如果實現該方法應該清除受影響的bean的所有元數據
	 */
	default void resetBeanDefinition(String beanName) {
	}

}

後者是 InstantiationAwareBeanPostProcessor 接口中的方法,定義如下:

public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {

	/**
	 * Bean 實例化前調用,返回非 {@code null} IoC 容器不會對 Bean 進行實例化 並且後續的生命周期回調方	  *	法不會調用,返回 {@code null} 則進行 IoC 容器對 Bean 的實例化
	 */
	@Nullable
	default Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
		return null;
	}

	/**
	 * Bean 實例化之後,屬性填充之前調用,返回 {@code true} 則進行默認的屬性填充步驟,返回 {@code 		 * false} 會跳過屬性填充階段。
	 */
	default boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
		return true;
	}

	/**
	 * Bean 實例化后屬性賦值前調用,PropertyValues 是已經封裝好的設置的屬性值,返回 {@code null} 繼續
	 * 使用現有屬性,否則會替換 PropertyValues。
	 * @since 5.1版本新加的和底下的方法一樣
	 */
	@Nullable
	default PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName)
			throws BeansException {
		return null;
	}

	/**
	 * 跟上面方法一樣的功能,只不過是5.1以前版本所使用的
	 * 返回 {@code null} 會跳過屬性填充階段
	 */
	@Deprecated
	@Nullable
	default PropertyValues postProcessPropertyValues(
			PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {

		return pvs;
	}

}

關於這兩個方法的調用時機,可以查看 Spring IoC createBean 方法詳解。

AutowiredAnnotationBeanPostProcessor#postProcessMergedBeanDefinition

首先執行的是 postProcessMergedBeanDefinition() 。

public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
    // 尋找需要注入的字段或方法,並封裝成 InjectionMetadata,見下文詳解
    InjectionMetadata metadata = findAutowiringMetadata(beanName, beanType, null);
    // 檢查元數據中的註解信息
    metadata.checkConfigMembers(beanDefinition);
}

InjectionMetadata 就是注入的元信息描述,主要字段如下:

public class InjectionMetadata {
    
    // 需要依賴注入的目標類
    private final Class<?> targetClass;
    // 注入元素的集合
    private final Collection<InjectedElement> injectedElements;
    
    // 忽略其它代碼
    
}

InjectedElement 就是注入的元素,主要字段如下:

public abstract static class InjectedElement {
    
    // 注入的屬性或方法
    protected final Member member;
    // 需要注入的是否是字段
    protected final boolean isField;
    
}

AutowiredAnnotationBeanPostProcessor#findAutowiringMetadata

private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) {
    // Fall back to class name as cache key, for backwards compatibility with custom callers.
    String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
    // Quick check on the concurrent map first, with minimal locking.
    // 首先從緩存中獲取
    InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
    // 判斷是否需要刷新,即metadata為null或者metadata中存儲的targetClass和當前clazz不等
    if (InjectionMetadata.needsRefresh(metadata, clazz)) {
        // 這裏相當於是一個double check,防止多線程出現的併發問題
        synchronized (this.injectionMetadataCache) {
            metadata = this.injectionMetadataCache.get(cacheKey);
            if (InjectionMetadata.needsRefresh(metadata, clazz)) {
                if (metadata != null) {
                    metadata.clear(pvs);
                }
                // 構建注入元信息,見下文詳解
                metadata = buildAutowiringMetadata(clazz);
                // 放入緩存中
                this.injectionMetadataCache.put(cacheKey, metadata);
            }
        }
    }
    // 返回注入元信息
    return metadata;
}

AutowiredAnnotationBeanPostProcessor#buildAutowiringMetadata

private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) {
    if (!AnnotationUtils.isCandidateClass(clazz, this.autowiredAnnotationTypes)) {
        return InjectionMetadata.EMPTY;
    }
    // 判斷當前類或其字段或其方法是否標註了autowiredAnnotationTypes中的註解,沒有的話直接返回空的
    List<InjectionMetadata.InjectedElement> elements = new ArrayList<>();
    Class<?> targetClass = clazz;

    do {
        final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>();
        // 遍歷targetClass中的字段
        ReflectionUtils.doWithLocalFields(targetClass, field -> {
            // 獲取field上的@Autowired註解信息
            MergedAnnotation<?> ann = findAutowiredAnnotation(field);
            if (ann != null) {
                // 如果字段是靜態類型是不會進行注入的
                if (Modifier.isStatic(field.getModifiers())) {
                    if (logger.isInfoEnabled()) {
                        logger.info("Autowired annotation is not supported on static fields: " + field);
                    }
                    return;
                }
                // 獲取@Autowired註解中的required屬性
                boolean required = determineRequiredStatus(ann);
                // 將裝成AutowiredFieldElement添加進currElements
                currElements.add(new AutowiredFieldElement(field, required));
            }
        });
        // 遍歷targetClass中的方法
        ReflectionUtils.doWithLocalMethods(targetClass, method -> {
            // 找到橋接方法
            Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
            // 判斷方法的可見性,如果不可見則直接返回
            if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
                return;
            }
            // 獲取method上的@Autowired註解信息
            MergedAnnotation<?> ann = findAutowiredAnnotation(bridgedMethod);
            if (ann != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
                // 如果是靜態方法是不會進行注入的
                if (Modifier.isStatic(method.getModifiers())) {
                    if (logger.isInfoEnabled()) {
                        logger.info("Autowired annotation is not supported on static methods: " + method);
                    }
                    return;
                }
                // 方法注入沒有參數就違背了初衷,就是在脫褲子放屁
                if (method.getParameterCount() == 0) {
                    if (logger.isInfoEnabled()) {
                        logger.info("Autowired annotation should only be used on methods with parameters: " + method);
                    }
                }
                // 獲取@Autowired註解中的required屬性
                boolean required = determineRequiredStatus(ann);
                // 將方法和目標類型封裝成屬性描述符
                PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
                // 封裝成AutowiredMethodElement添加進currElements
                currElements.add(new AutowiredMethodElement(method, required, pd));
            }
        });
        // 將currElements整個添加進elements
        elements.addAll(0, currElements);
        // 獲取targetClass的父類,進行下一次循環
        targetClass = targetClass.getSuperclass();
    }
    // 當targetClass為空或者targetClass等於Object.class時會退出循環
    while (targetClass != null && targetClass != Object.class);
    // 將elements和clazz封裝成InjectionMetadata返回
    return InjectionMetadata.forElements(elements, clazz);
}

上面代碼中的 findAutowiredAnnotation() 就是在遍歷 autowiredAnnotationTypes 屬性,看字段或者方法上的註解是否存在於 autowiredAnnotationTypes 中,或者其派生註解,找到第一個就返回,不會再繼續遍歷了。

public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter
		implements MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware {
    
    private final Set<Class<? extends Annotation>> autowiredAnnotationTypes = new LinkedHashSet<>(4);
    
    public AutowiredAnnotationBeanPostProcessor() {
        this.autowiredAnnotationTypes.add(Autowired.class);
        this.autowiredAnnotationTypes.add(Value.class);
        try {
            this.autowiredAnnotationTypes.add((Class<? extends Annotation>)
                                              ClassUtils.forName("javax.inject.Inject", AutowiredAnnotationBeanPostProcessor.class.getClassLoader()));
            logger.trace("JSR-330 'javax.inject.Inject' annotation found and supported for autowiring");
        }
        catch (ClassNotFoundException ex) {
            // JSR-330 API not available - simply skip.
        }
	}
    
}

從 AutowiredAnnotationBeanPostProcessor 類的構造函數中,我們可以發現 autowiredAnnotationTypes 默認添加了 @Autowired、@Value 以及 @Inject (在 JSR-330 的jar包存在於當前環境時)。

至此,使用 @Autowired 修飾的字段和方法已經封裝成 InjectionMetadata 並放在 injectionMetadataCache 緩存中,便於後續使用。

AutowireAnnotationBeanPostProcessor#postProcessProperties

postProcessMergedBeanDefinition() 調用后 bean 就會進行實例化接着調用 postProcessProperties() 。

public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
    // 獲取緩存中的 InjectionMetadata
    InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
    try {
        // 進行屬性的注入
        metadata.inject(bean, beanName, pvs);
    }
    catch (BeanCreationException ex) {
        throw ex;
    }
    catch (Throwable ex) {
        throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
    }
    // 返回注入的屬性
    return pvs;
}

// InjectMetadata.java
public void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
    // 獲取檢查后的元素
    Collection<InjectedElement> checkedElements = this.checkedElements;
    // 如果checkedElements不為空就使用checkedElements,否則使用injectedElements
    Collection<InjectedElement> elementsToIterate =
        (checkedElements != null ? checkedElements : this.injectedElements);
    if (!elementsToIterate.isEmpty()) {
        // 遍歷elementsToIterate
        for (InjectedElement element : elementsToIterate) {
            if (logger.isTraceEnabled()) {
                logger.trace("Processing injected element of bean '" + beanName + "': " + element);
            }
            // AutowiredFieldElement、AutowiredMethodElement這兩個類繼承InjectionMetadata.InjectedElement,各自重寫了inject方法
            element.inject(target, beanName, pvs);
        }
    }
}

AutowiredFieldElement#inject

protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
    // 強轉成Field類型
    Field field = (Field) this.member;
    Object value;
    if (this.cached) {
        // 如果緩存過,直接使用緩存的值,一般第一次注入都是false
        value = resolvedCachedArgument(beanName, this.cachedFieldValue);
    }
    else {
        // 構建依賴描述符
        DependencyDescriptor desc = new DependencyDescriptor(field, this.required);
        desc.setContainingClass(bean.getClass());
        Set<String> autowiredBeanNames = new LinkedHashSet<>(1);
        Assert.state(beanFactory != null, "No BeanFactory available");
        // 獲取類型轉換器
        TypeConverter typeConverter = beanFactory.getTypeConverter();
        try {
            // 進行依賴解決,獲取符合條件的bean
            value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
        }
        catch (BeansException ex) {
            throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex);
        }
        // 加鎖
        synchronized (this) {
            // 如果沒有被緩存
            if (!this.cached) {
                // 找到了需要的bean || 該字段是必要的
                if (value != null || this.required) {
                    // 將依賴描述符賦值給cachedFieldValue
                    this.cachedFieldValue = desc;
                    // 註冊bean的依賴關係,用於檢測是否循環依賴
                    registerDependentBeans(beanName, autowiredBeanNames);
                    // 如果符合條件的bean只有一個
                    if (autowiredBeanNames.size() == 1) {
                        String autowiredBeanName = autowiredBeanNames.iterator().next();
                        // beanFactory含有名為autowiredBeanName的bean && 類型是匹配的
                        if (beanFactory.containsBean(autowiredBeanName) &&
                            beanFactory.isTypeMatch(autowiredBeanName, field.getType())) {
                            // 將該屬性解析到的bean的信息封裝成ShortcutDependencyDescriptor
                            // 之後可以通過調用resolveShortcut()來間接調beanFactory.getBean()快速獲取bean
                            this.cachedFieldValue = new ShortcutDependencyDescriptor(
                                desc, autowiredBeanName, field.getType());
                        }
                    }
                }
                else {
                    this.cachedFieldValue = null;
                }
                // 緩存標識設置為true
                this.cached = true;
            }
        }
    }
    // 如果找到了符合的bean,設置字段可訪問,利用反射設置值
    if (value != null) {
        ReflectionUtils.makeAccessible(field);
        field.set(bean, value);
    }
}

上面代碼中的 beanFactory.resolveDependency() 在 Spring IoC createBean 方法詳解 一文中有介紹過,這裏不再贅述;同樣 registerDependentBeans() 最終會調用 DefaultSingletonBeanRegistry.registerDependentBean() ,該方法在 Spring IoC getBean 方法詳解 一文中有介紹過,這裏也不再贅述。

AutowiredMethodElement#inject

protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
    // 檢查是否需要跳過
    if (checkPropertySkipping(pvs)) {
        return;
    }
    // 強轉成Method類型
    Method method = (Method) this.member;
    Object[] arguments;
    if (this.cached) {
        // Shortcut for avoiding synchronization...
        // 如果緩存過,直接調用beanFactory.resolveDependency()返回符合的bean
        arguments = resolveCachedArguments(beanName);
    }
    else {
        // 獲取參數數量
        int argumentCount = method.getParameterCount();
        arguments = new Object[argumentCount];
        // 創建依賴描述符數組
        DependencyDescriptor[] descriptors = new DependencyDescriptor[argumentCount];
        // 記錄用於自動注入bean的名稱集合
        Set<String> autowiredBeans = new LinkedHashSet<>(argumentCount);
        Assert.state(beanFactory != null, "No BeanFactory available");
        // 獲取類型轉換器
        TypeConverter typeConverter = beanFactory.getTypeConverter();
        // 遍歷參數
        for (int i = 0; i < arguments.length; i++) {
            // 將方法和參數的下標構建成MethodParameter,這裏面主要記錄了參數的下標和類型
            MethodParameter methodParam = new MethodParameter(method, i);
            // 將MethodParameter構建成DependencyDescriptor
            DependencyDescriptor currDesc = new DependencyDescriptor(methodParam, this.required);
            currDesc.setContainingClass(bean.getClass());
            descriptors[i] = currDesc;
            try {
                // 進行依賴解決,找到符合條件的bean
                Object arg = beanFactory.resolveDependency(currDesc, beanName, autowiredBeans, typeConverter);
                if (arg == null && !this.required) {
                    arguments = null;
                    break;
                }
                arguments[i] = arg;
            }
            catch (BeansException ex) {
                throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(methodParam), ex);
            }
        }
        // 這裏跟字段注入差不多,就是註冊bean的依賴關係,並且緩存每個參數的ShortcutDependencyDescriptor
        synchronized (this) {
            if (!this.cached) {
                if (arguments != null) {
                    DependencyDescriptor[] cachedMethodArguments = Arrays.copyOf(descriptors, arguments.length);
                    registerDependentBeans(beanName, autowiredBeans);
                    if (autowiredBeans.size() == argumentCount) {
                        Iterator<String> it = autowiredBeans.iterator();
                        Class<?>[] paramTypes = method.getParameterTypes();
                        for (int i = 0; i < paramTypes.length; i++) {
                            String autowiredBeanName = it.next();
                            if (beanFactory.containsBean(autowiredBeanName) &&
                                beanFactory.isTypeMatch(autowiredBeanName, paramTypes[i])) {
                                cachedMethodArguments[i] = new ShortcutDependencyDescriptor(descriptors[i], autowiredBeanName, paramTypes[i]);
                            }
                        }
                    }
                    this.cachedMethodArguments = cachedMethodArguments;
                }
                else {
                    this.cachedMethodArguments = null;
                }
                this.cached = true;
            }
        }
    }
    // 找到了符合條件的bean
    if (arguments != null) {
        try {
            // 設置方法可訪問,利用反射進行方法調用,傳入參數
            ReflectionUtils.makeAccessible(method);
            method.invoke(bean, arguments);
        }
        catch (InvocationTargetException ex) {
            throw ex.getTargetException();
        }
    }
}

構造器注入

構造器注入就是通過調用 determineCandidateConstructors() 來返回合適的構造器。

public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, final String beanName) throws BeanCreationException {

    // Quick check on the concurrent map first, with minimal locking.
    // 首先從緩存中獲取
    Constructor<?>[] candidateConstructors = this.candidateConstructorsCache.get(beanClass);
    // 緩存為空
    if (candidateConstructors == null) {
        // Fully synchronized resolution now...
        // 這裏相當於double check
        synchronized (this.candidateConstructorsCache) {
            candidateConstructors = this.candidateConstructorsCache.get(beanClass);
            if (candidateConstructors == null) {
                Constructor<?>[] rawCandidates;
                try {
                    // 獲取beanClass的所有構造函數
                    rawCandidates = beanClass.getDeclaredConstructors();
                }
                catch (Throwable ex) {
                    throw new BeanCreationException(beanName, "Resolution of declared constructors on bean Class [" + beanClass.getName() +"] from ClassLoader [" + beanClass.getClassLoader() + "] failed", ex);
                }
                // 存放標註了@Autowired註解的構造器
                List<Constructor<?>> candidates = new ArrayList<>(rawCandidates.length);
                // 存放標註了@Autowired註解,並且required為true的構造器
                Constructor<?> requiredConstructor = null;
                Constructor<?> defaultConstructor = null;
                for (Constructor<?> candidate : rawCandidates) {
                    // 獲取構造器上的@Autowired註解信息
                    MergedAnnotation<?> ann = findAutowiredAnnotation(candidate);
                    if (ann == null) {
                        // 如果沒有從候選者找到註解,則嘗試解析beanClass的原始類(針對CGLIB代理)
                        Class<?> userClass = ClassUtils.getUserClass(beanClass);
                        if (userClass != beanClass) {
                            try {
                                Constructor<?> superCtor =
userClass.getDeclaredConstructor(candidate.getParameterTypes());
                                ann = findAutowiredAnnotation(superCtor);
                            }
                            catch (NoSuchMethodException ex) {
                                // Simply proceed, no equivalent superclass constructor found...
                            }
                        }
                    }
                    if (ann != null) {
                        // 如果requiredConstructor不為空,代表有多個標註了@Autowired且required為true的構造器,此時Spring不知道選擇哪個拋出異常
                        if (requiredConstructor != null) {
                            throw new BeanCreationException(beanName, "Invalid autowire-marked constructor: " + candidate +". Found constructor with 'required' Autowired annotation already: " + requiredConstructor);
                        }
                        // 獲取@Autowired註解的reuired屬性的值
                        boolean required = determineRequiredStatus(ann);
                        if (required) {
                            // 如果當前候選者是@Autowired(required = true),則之前不能存在其他使用@Autowire註解的構造函數,否則拋異常
                            if (!candidates.isEmpty()) {
                                throw new BeanCreationException(beanName,"Invalid autowire-marked constructors: " + candidates +". Found constructor with 'required' Autowired annotation: " + candidate);
                            }
                            // required為true將當前構造器賦值給requiredConstructor
                            requiredConstructor = candidate;
                        }
                        // 將當前構造器加入進候選構造器中
                        candidates.add(candidate);
                    }
                    // 沒有標註了@Autowired註解且參數長度為0,賦值為默認構造器
                    else if (candidate.getParameterCount() == 0) {
                        defaultConstructor = candidate;
                    }
                }
                // 有標註了@Autowired註解的構造器
                if (!candidates.isEmpty()) {
                    // Add default constructor to list of optional constructors, as fallback.
                    // 沒有標註了@Autowired且required為true的構造器
                    if (requiredConstructor == null) {
                        // 默認構造器不為空
                        if (defaultConstructor != null) {
                            // 將默認構造器加入進候選構造器中
                            candidates.add(defaultConstructor);
                        }
                    }
                    // 將候選者賦值給candidateConstructors
                    candidateConstructors = candidates.toArray(new Constructor<?>[0]);
                }
                // 只有1個構造器 && 參數長度大於0(非默認構造器),只能用它當做候選者了
                else if (rawCandidates.length == 1 && rawCandidates[0].getParameterCount() > 0) {
                    candidateConstructors = new Constructor<?>[] {rawCandidates[0]};
                }
                // 只有1個構造器 && 參數長度大於0,只能用它當做候選者了
                else if (nonSyntheticConstructors == 2 && primaryConstructor != null &&
                         defaultConstructor != null && !primaryConstructor.equals(defaultConstructor)) {
                    candidateConstructors = new Constructor<?>[] {primaryConstructor, defaultConstructor};
                }
                else if (nonSyntheticConstructors == 1 && primaryConstructor != null) {
                    candidateConstructors = new Constructor<?>[] {primaryConstructor};
                }
                // 返回一個空的Constructor
                else {
                    candidateConstructors = new Constructor<?>[0];
                }
                // 緩存候選的構造器
                this.candidateConstructorsCache.put(beanClass, candidateConstructors);
            }
        }
    }
    // 如果候選構造器長度大於0,直接返回,否則返回null
    return (candidateConstructors.length > 0 ? candidateConstructors : null);
}

關於 SmartInstantiationAwareBeanPostProcessor 接口的調用時機,在 Spring IoC createBean 方法詳解 一文中有介紹過,這裏就不再贅述了。

總結

本文主要介紹了 Spring 對 @Autowired 註解的主要處理過程,結合前面的 Spring IoC getBean 方法詳解 和 Spring IoC createBean 方法詳解 文章一起看才能更好的理解。

最後,我模仿 Spring 寫了一個精簡版,代碼會持續更新。地址:https://github.com/leisurexi/tiny-spring。

本站聲明:網站內容來源於博客園,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

※網頁設計一頭霧水該從何著手呢? 台北網頁設計公司幫您輕鬆架站!

※網頁設計公司推薦不同的風格,搶佔消費者視覺第一線

※Google地圖已可更新顯示潭子電動車充電站設置地點!!

※廣告預算用在刀口上,台北網頁設計公司幫您達到更多曝光效益

※別再煩惱如何寫文案,掌握八大原則!

※網頁設計最專業,超強功能平台可客製化

淺談Unity的腳本執行順序

一、添加腳本的順序

這是一張官方的腳本順序圖

 

一般,當我們把腳本綁定在遊戲對象上時,或者點擊綁定好的腳本的reset按鈕時,會調用Reset()

當我們初始化一個對象時,會先調用Awake()在調用OnEnable()

GameObject.instantiate(o);

start()在第一次調用update()前調用,有時候start()會在Awake(),OnEnable()執行完后立刻執行,處於同一幀

onDisable()和onDestroy()的執行順序有點特別:

第一種情況:

  對於不同對象上的不同的腳本,執行是沒有先後規律的,且必須成對執行(調用完了onDisable()必須再調用onDestroy())

  eg:

gameobject1:
    sc1.cs
    sc2.cs
gameobject2:
    sc3.cs
    sc4.cs
gameobject3:
    sc5.cs
    sc6.cs

gameobject1.sc1.onDisable()->gameobject1.sc1.onDestroy()->gameobject3.sc5.onDisable()->

gameobject3.sc5.onDestroy()

[如果按前面的規則的話,應該先執行gameobject3的腳本,但這裏不是]

第二種情況:

在同一個對象的不同的腳本上,這兩個方法按照腳本

在m_component中的索引按順序執行的,而且不是成對執行,索引自小到大執行,最早加入的最早調用onDisable()和onDestroy()

gemeobject2.sc3.onDisable()->gameobject2.sc4.onDisable()->

gameobject2.sc3.onDestroy->gameobject2.sc4.onDestroy()

這裏這些腳本先依次調用onDisable()才調用onDestroy()。

二、如何自定義多個腳本的執行順序

 

 划重點:在unity裏面可以點擊edit->project settings->Script->Execution Order中自定義腳本執行順序,

當我們沒有設置腳本執行順序時,腳本按照Default Time的標準執行(你可以把unity裏面hireachy裏面添加對象和在inspector裏面添加腳本

視作一個棧,按照先進先出原則,優先執行后添加的對象的先添加的Script。

可以單擊+號添加對象到執行列表中

1是腳本的執行順序,當你的值execution order越小時,越先執行,在default time上方的在執行default time前執行,在default time下方

的在default time后執行

上面的設置,是通過修改每一個腳本對應的meta文件(去自己的代碼目錄看一下)的excution order來實現的。

 

 三、腳本執行順序的本質

在我們的場景文件.unity,場景文件是一個YAML文檔

 

 每一個腳本對應一個fileid,fileid越小越有先執行

 4.運用

如果你的腳本A會用到另一個腳本B中的某一個對象c,為了防止你在B初始化之前去調用c,出現空指針,你必須讓腳本B在A之後掛載(這樣B就會先初始化),

還有一個很重要的地方,你必須把對象c的初始化寫在腳本B的Awake()方法裏面,因為start()並不是在初始化就立刻調用的,而是在當前更新一幀時,start()

會在update()第一次調用前調用一次,這樣的話如果你把對象c的初始化寫在腳本B的start()方法裏面,很有可能所有腳本的awake()都跑完了,對象c卻沒有初始化,

這樣就出現了空指針。因此,把對象c的初始化在腳本B的awake()方法,而把調用對象c寫在腳本A的start()足夠安全

本站聲明:網站內容來源於博客園,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

※自行創業缺乏曝光? 網頁設計幫您第一時間規劃公司的形象門面

※網頁設計一頭霧水該從何著手呢? 台北網頁設計公司幫您輕鬆架站!

※想知道最厲害的網頁設計公司"嚨底家"!

※別再煩惱如何寫文案,掌握八大原則!

※產品缺大量曝光嗎?你需要的是一流包裝設計!

03 . Django之騰訊雲短信

簡介

由於項目在註冊、登錄、找回密碼 時需要發送短信驗證的功能,我們使用騰訊雲短信做。

為什麼要用騰訊雲短信呢? 因為註冊就送 100條免費短信 的額度。

實現

註冊騰訊雲

註冊一個騰訊雲賬戶,騰訊雲中提供了很多功能:雲服務器、雲存儲你、雲直播、雲短信等很多功能。

註冊地址:https://cloud.tencent.com/

註冊並要實名認證

開通雲短信

創建應用

創建應用並將應用中生成的 SDK AppID和 App Key 複製下來,之後通過python發送短信時需要用到。

創建簽名

在騰訊雲短信簽名時需要認證,認證需要填寫簽名類型:網站、APP、小程序、公眾號,前三種需要提供企業資質等複雜的東西,個人公眾號認證會比較便捷,所以推薦個人開發的話使用 公眾號 進行簽名。

so,咱們需要先 申請一個公眾號 然後 創建簽名

申請微信訂閱號

註冊地址:https://mp.weixin.qq.com/

創建簽名

創建模板

發送短信

上述的準備工作做完中我們開通相關服務並獲取到如下幾個值:

# 創建應用,獲取到 appid 和 appkey
# 創建簽名,獲取 簽名內容
# 創建模板,獲取 模板ID

接下來開始使用Python發送短信。

安裝SDK

 pip install qcloudsms_py

基於SDK發送短信

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import ssl
# ssl._create_default_https_context = ssl._create_unverified_context
from qcloudsms_py import SmsMultiSender, SmsSingleSender
from qcloudsms_py.httpclient import HTTPError
def send_sms_single(phone_num, template_id, template_param_list):
    """
    單條發送短信
    :param phone_num: 手機號
    :param template_id: 騰訊雲短信模板ID
    :param template_param_list: 短信模板所需參數列表,例如:【驗證碼:{1},描述:{2}】,則傳遞參數 [888,666]按順序去格式化模板
    :return:
    """
    appid = 112142311  # 自己應用ID
    appkey = "8cc5b87123y423433412387930004"  # 自己應用Key
    sms_sign = "幽夢DevOps"  # 自己騰訊雲創建簽名時填寫的簽名內容(使用公眾號的話這個值一般是公眾號全稱或簡稱)
    sender = SmsSingleSender(appid, appkey)
    try:
        response = sender.send_with_param(86, phone_num, template_id, template_param_list, sign=sms_sign)
    except HTTPError as e:
        response = {'result': 1000, 'errmsg': "網絡異常發送失敗"}
    return response
def send_sms_multi(phone_num_list, template_id, param_list):
    """
    批量發送短信
    :param phone_num_list:手機號列表
    :param template_id:騰訊雲短信模板ID
    :param param_list:短信模板所需參數列表,例如:【驗證碼:{1},描述:{2}】,則傳遞參數 [888,666]按順序去格式化模板
    :return:
    """
    appid = 112142311
    appkey = "8cc5b87123y423423412387930004"
    sms_sign = "幽夢DevOps"
    sender = SmsMultiSender(appid, appkey)
    try:
        response = sender.send_with_param(86, phone_num_list, template_id, param_list, sign=sms_sign)
    except HTTPError as e:
        response = {'result': 1000, 'errmsg': "網絡異常發送失敗"}
    return response
if __name__ == '__main__':
    result1 = send_sms_single("18621048481", 548760, [666, ])
    print(result1)
    result2 = send_sms_single( ["18621048481", "15131255089", "15131255089", ],548760, [999, ])
    print(result2)
關於頻率限制

騰訊雲短信後台可以進行 短信頻率 的限制。

但是,由於我們是免費用戶所以無法進行設置,只能使用默認的配置(30秒發1條/1小時發5條/1天發10條)。

!

本站聲明:網站內容來源於博客園,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

※別再煩惱如何寫文案,掌握八大原則!

※網頁設計一頭霧水該從何著手呢? 台北網頁設計公司幫您輕鬆架站!

※超省錢租車方案

※教你寫出一流的銷售文案?

※網頁設計最專業,超強功能平台可客製化

※產品缺大量曝光嗎?你需要的是一流包裝設計!

SpringCloud之Security

Spring Security是Spring提供的一個安全框架,提供認證和授權功能,最主要的是它提供了簡單的使用方式,同時又有很高的靈活性,簡單,靈活,強大。

我個人博客系統採用的權限框架就是Spring Security,正好整合到SpringCloud裏面。

一般系統里關於角色方面通常有這麼幾張表,角色表、用戶-角色表、菜單表、角色-菜單表等。

不過我個人博客系統主要以wordpress作為參考,沿用其12張表,如圖:

 

 

一、導入Maven依賴

<properties>
       <jjwt.version>0.9.0</jjwt.version>
       <spring-security-jwt.version>1.0.9.RELEASE</spring-security-jwt.version>
</properties>
 <!-- springsecurity-->
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-security</artifactId>
       </dependency>
       <dependency>
           <groupId>org.springframework.security</groupId>
           <artifactId>spring-security-jwt</artifactId>
           <version>${spring-security-jwt.version}</version>
       </dependency>
       <dependency>
           <groupId>io.jsonwebtoken</groupId>
           <artifactId>jjwt</artifactId>
           <version>${jjwt.version}</version>
       </dependency>

二、編寫Spring Security配置類

package com.springcloud.blog.admin.config;
import com.springcloud.blog.admin.security.UserAuthenticationProvider;
import com.springcloud.blog.admin.security.UserPermissionEvaluator;
import com.springcloud.blog.admin.security.handler.*;
import com.springcloud.blog.admin.security.jwt.JWTAuthenticationTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler;

/**
 * SpringSecurity配置類
 * @Author youcong
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) //開啟權限註解,默認是關閉的
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 自定義登錄成功處理器
     */
    @Autowired
    private UserLoginSuccessHandler userLoginSuccessHandler;
    /**
     * 自定義登錄失敗處理器
     */
    @Autowired
    private UserLoginFailureHandler userLoginFailureHandler;
    /**
     * 自定義註銷成功處理器
     */
    @Autowired
    private UserLogoutSuccessHandler userLogoutSuccessHandler;
    /**
     * 自定義暫無權限處理器
     */
    @Autowired
    private UserAuthAccessDeniedHandler userAuthAccessDeniedHandler;
    /**
     * 自定義未登錄的處理器
     */
    @Autowired
    private UserAuthenticationEntryPointHandler userAuthenticationEntryPointHandler;
    /**
     * 自定義登錄邏輯驗證器
     */
    @Autowired
    private UserAuthenticationProvider userAuthenticationProvider;

    /**
     * 加密方式
     * @Author youcong
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }
    /**
     * 注入自定義PermissionEvaluator
     */
    @Bean
    public DefaultWebSecurityExpressionHandler userSecurityExpressionHandler(){
        DefaultWebSecurityExpressionHandler handler = new DefaultWebSecurityExpressionHandler();
        handler.setPermissionEvaluator(new UserPermissionEvaluator());
        return handler;
    }

    /**
     * 配置登錄驗證邏輯
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth){
        //這裏可啟用我們自己的登陸驗證邏輯
        auth.authenticationProvider(userAuthenticationProvider);
    }
    /**
     * 配置security的控制邏輯
     * @Author youcong
     * @Param  http 請求
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                // 不進行權限驗證的請求或資源(從配置文件中讀取)
                .antMatchers(JWTConfig.antMatchers.split(",")).permitAll()
                // .antMatchers("/*").permitAll()
                // 其他的需要登陸后才能訪問
                .anyRequest().authenticated()
                .and()
                // 配置未登錄自定義處理類
                .httpBasic().authenticationEntryPoint(userAuthenticationEntryPointHandler)
                .and()
                // 配置登錄地址
                .formLogin()
                .loginProcessingUrl("/login/userLogin")
                // 配置登錄成功自定義處理類
                .successHandler(userLoginSuccessHandler)
                // 配置登錄失敗自定義處理類
                .failureHandler(userLoginFailureHandler)
                .and()
                // 配置登出地址
                .logout()
                .logoutUrl("/login/userLogout")
                // 配置用戶登出自定義處理類
                .logoutSuccessHandler(userLogoutSuccessHandler)
                .and()
                // 配置沒有權限自定義處理類
                .exceptionHandling().accessDeniedHandler(userAuthAccessDeniedHandler)
                .and()
                // 開啟跨域
                .cors()
                .and()
                // 取消跨站請求偽造防護
                .csrf().disable();
        // 基於Token不需要session
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        // 禁用緩存
        http.headers().cacheControl();
        // 添加JWT過濾器
        http.addFilter(new JWTAuthenticationTokenFilter(authenticationManager()));
    }
}

三、編寫JWTConfig和application.yml增加jwt相關配置

package com.springcloud.blog.admin.config;
import lombok.Getter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * JWT配置類
 * @Author youcong
 */
@Getter
@Component
@ConfigurationProperties(prefix = "jwt")
public class JWTConfig {
    /**
     * 密鑰KEY
     */
    public static String secret;
    /**
     * TokenKey
     */
    public static String tokenHeader;
    /**
     * Token前綴字符
     */
    public static String tokenPrefix;
    /**
     * 過期時間
     */
    public static Integer expiration;
    /**
     * 不需要認證的接口
     */
    public static String antMatchers;


    public void setSecret(String secret) {
        this.secret = secret;
    }

    public void setTokenHeader(String tokenHeader) {
        this.tokenHeader = tokenHeader;
    }

    public void setTokenPrefix(String tokenPrefix) {
        this.tokenPrefix = tokenPrefix;
    }

    public void setExpiration(Integer expiration) {
        this.expiration = expiration * 1000;
    }

    public void setAntMatchers(String antMatchers) {
        this.antMatchers = antMatchers;
    }


}

application.yml增加如下內容:

# JWT配置
jwt:
  # 密匙KEY
  secret: JWTSecret
  # HeaderKEY
  tokenHeader: Authorization
  # Token前綴字符
  tokenPrefix: challenger-
  # 過期時間 單位秒 1天後過期=86400 7天後過期=604800
  expiration: 86400
  # 配置不需要認證的接口
  antMatchers: /index/**,/login/**,/favicon.ico
  # 有效時間
  validTime: 7

四、編寫過濾器處理類

1.UserLoginSuccessHandler.java

package com.springcloud.blog.admin.security.handler;


import com.springcloud.blog.admin.config.JWTConfig;
import com.springcloud.blog.admin.security.entity.SelfUserEntity;
import com.springcloud.blog.admin.utils.AccessAddressUtil;
import com.springcloud.blog.admin.utils.JWTTokenUtil;
import com.springcloud.blog.admin.utils.RedisUtil;
import com.springcloud.blog.admin.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description 登錄成功處理類
 * @Author youcong
 */
@Component
public class UserLoginSuccessHandler implements AuthenticationSuccessHandler {


    /**
     * 登錄成功返回結果
     * @Author youcong
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication){
        // 組裝JWT
        SelfUserEntity selfUserEntity =  (SelfUserEntity) authentication.getPrincipal();
        String token = JWTTokenUtil.createAccessToken(selfUserEntity);
        token = JWTConfig.tokenPrefix + token;

        // 封裝返回參數
        Map<String,Object> resultData = new HashMap<>();
        resultData.put("code","200");
        resultData.put("msg", "登錄成功");
        resultData.put("token",token);
        ResultUtil.responseJson(response,resultData);
    }
}

2.UserLoginFailureHandler.java

package com.springcloud.blog.admin.security.handler;


import com.springcloud.blog.admin.utils.ResultUtil;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description 登錄失敗處理類
 * @Author youcong
 */
@Component
public class UserLoginFailureHandler implements AuthenticationFailureHandler {
    /**
     * 登錄失敗返回結果
     * @Author youcong
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception){
        // 這些對於操作的處理類可以根據不同異常進行不同處理
        if (exception instanceof UsernameNotFoundException){
            System.out.println("【登錄失敗】"+exception.getMessage());
            ResultUtil.responseJson(response,ResultUtil.resultCode(500,"用戶名不存在"));
        }
        if (exception instanceof LockedException){
            System.out.println("【登錄失敗】"+exception.getMessage());
            ResultUtil.responseJson(response,ResultUtil.resultCode(500,"用戶被凍結"));
        }
        if (exception instanceof BadCredentialsException){
            System.out.println("【登錄失敗】"+exception.getMessage());
            ResultUtil.responseJson(response,ResultUtil.resultCode(500,"密碼錯誤"));
        }
        ResultUtil.responseJson(response,ResultUtil.resultCode(500,"登錄失敗"));
    }
}

3.UserLogoutSuccessHandler.java

package com.springcloud.blog.admin.security.handler;


import com.springcloud.blog.admin.utils.DateUtil;
import com.springcloud.blog.admin.utils.RedisUtil;
import com.springcloud.blog.admin.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 登出成功處理類
 * @Author youcong
 */
@Component
public class UserLogoutSuccessHandler implements LogoutSuccessHandler {
    

    /**
     * 用戶登出返回結果
     * 這裏應該讓前端清除掉Token
     * @Author youcong
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication){

        Map<String,Object> resultData = new HashMap<>();
        resultData.put("code","200");
        resultData.put("msg", "登出成功");
        SecurityContextHolder.clearContext();
        ResultUtil.responseJson(response,ResultUtil.resultSuccess(resultData));
    }
}

4.UserAuthAccessDeniedHandler.java

package com.springcloud.blog.admin.security.handler;
import com.springcloud.blog.admin.utils.ResultUtil;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description 暫無權限處理類
 * @Author youcong
 */
@Component
public class UserAuthAccessDeniedHandler implements AccessDeniedHandler {
    /**
     * 暫無權限返回結果
     * @Author youcong
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException exception){
        ResultUtil.responseJson(response,ResultUtil.resultCode(403,"未授權"));
    }
}

5.UserAuthenticationEntryPointHandler.java

package com.springcloud.blog.admin.security.handler;


import com.springcloud.blog.admin.utils.ResultUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用戶未登錄處理類
 * @Author youcong
 */
@Component
public class UserAuthenticationEntryPointHandler implements AuthenticationEntryPoint {
    /**
     * 用戶未登錄返回結果
     * @Author youcong
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception){
        ResultUtil.responseJson(response,ResultUtil.resultCode(401,"未登錄"));
    }
}

6.UserAuthenticationProvider.java

自定義登錄驗證這個類,需要根據實際情況重寫。通常來說改動不大。

package com.springcloud.blog.admin.security;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.springcloud.blog.admin.entity.Usermeta;
import com.springcloud.blog.admin.entity.Users;
import com.springcloud.blog.admin.security.entity.SelfUserEntity;
import com.springcloud.blog.admin.service.UsermetaService;
import com.springcloud.blog.admin.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 自定義登錄驗證
 *
 * @Author youcong
 */
@Component
public class UserAuthenticationProvider implements AuthenticationProvider {


    @Autowired
    private UsersService usersService;

    @Autowired
    private UsermetaService usermetaService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 獲取表單輸入中返回的用戶名
        String userName = (String) authentication.getPrincipal();
        // 獲取表單中輸入的密碼
        String password = (String) authentication.getCredentials();
        // 查詢用戶是否存在
         SelfUserEntity userInfo = usersService.getUserInfo(userName);


        if (userInfo.getUsername() == null || userInfo.getUsername() == "") {
            throw new UsernameNotFoundException("用戶名不存在");
        }


        // 我們還要判斷密碼是否正確,這裏我們的密碼使用BCryptPasswordEncoder進行加密的
        if (!new BCryptPasswordEncoder().matches(password, userInfo.getPassword())) {
            throw new BadCredentialsException("密碼不正確");
        }
        // 還可以加一些其他信息的判斷,比如用戶賬號已停用等判斷
        if (userInfo.getStatus().equals("1")) {
            throw new LockedException("該用戶已被凍結");
        }
        // 角色集合
        Set<GrantedAuthority> authorities = new HashSet<>();

        EntityWrapper<Usermeta> roleWrapper = new EntityWrapper<>();
        roleWrapper.eq("user_id",userInfo.getUserId());
        roleWrapper.eq("meta_key","wp_user_level");
        // 查詢用戶角色
        List<Usermeta> sysRoleEntityList = usermetaService.selectList(roleWrapper);
        for (Usermeta sysRoleEntity: sysRoleEntityList){
            authorities.add(new SimpleGrantedAuthority("ROLE_" + sysRoleEntity.getMetaValue()));
        }
        userInfo.setAuthorities(authorities);
        // 進行登錄
        return new UsernamePasswordAuthenticationToken(userInfo, password, authorities);
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }
}

7.UserPermissionEvaluator.java

package com.springcloud.blog.admin.security;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.springcloud.blog.admin.entity.Usermeta;
import com.springcloud.blog.admin.service.UsermetaService;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 自定義權限註解驗證
 * @Author youcong
 */
@Component
public class UserPermissionEvaluator implements PermissionEvaluator {

    @Autowired
    private UsermetaService usermetaService;

    /**
     * hasPermission鑒權方法
     * 這裏僅僅判斷PreAuthorize註解中的權限表達式
     * 實際中可以根據業務需求設計數據庫通過targetUrl和permission做更複雜鑒權
     * 當然targetUrl不一定是URL可以是數據Id還可以是管理員標識等,這裏根據需求自行設計
     * @Author youcong
     * @Param  authentication  用戶身份(在使用hasPermission表達式時Authentication參數默認會自動帶上)
     * @Param  targetUrl  請求路徑
     * @Param  permission 請求路徑權限
     * @Return boolean 是否通過
     */
    @Override
    public boolean hasPermission(Authentication authentication, Object targetUrl, Object permission) {
        // 獲取用戶信息
        Usermeta selfUserEntity =(Usermeta) authentication.getPrincipal();
        // 查詢用戶權限(這裏可以將權限放入緩存中提升效率)
        Set<String> permissions = new HashSet<>();
        EntityWrapper<Usermeta> roleWrapper = new EntityWrapper<>();
        roleWrapper.eq("user_id",selfUserEntity.getUserId());
        roleWrapper.eq("meta_key","wp_user_level");
        List<Usermeta> sysMenuEntityList = usermetaService.selectList(roleWrapper);
        for (Usermeta sysMenuEntity:sysMenuEntityList) {
            permissions.add(sysMenuEntity.getMetaValue());
        }
        // 權限對比
        if (permissions.contains(permission.toString())){
            return true;
        }
        return true;
    }
    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
        return false;
    }
}

五、編寫實體類

package com.springcloud.blog.admin.security.entity;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.Serializable;
import java.util.Collection;
import java.util.Map;

/**
 * SpringSecurity用戶的實體
 * 注意:這裏必須要實現UserDetails接口
 *
 * @Author youcong
 */
public class SelfUserEntity implements Serializable, UserDetails {

    private static final long serialVersionUID = 1L;

    /**
     * 用戶ID
     */
    private Long userId;
    /**
     * 用戶名
     */
    private String username;
    /**
     * 密碼
     */
    private String password;
    /**
     * 狀態
     */
    private String status;


    /**
     * 显示名稱
     */
    private String displayName;


    /**
     * 用戶參數
     */
    private Map<String, String> userParamMap;


    /**
     * 用戶角色
     */
    private Collection<GrantedAuthority> authorities;
    /**
     * 賬戶是否過期
     */
    private boolean isAccountNonExpired = false;
    /**
     * 賬戶是否被鎖定
     */
    private boolean isAccountNonLocked = false;
    /**
     * 證書是否過期
     */
    private boolean isCredentialsNonExpired = false;
    /**
     * 賬戶是否有效
     */
    private boolean isEnabled = true;


    public static long getSerialVersionUID() {
        return serialVersionUID;
    }

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    @Override
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Override
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }


    public void setAuthorities(Collection<GrantedAuthority> authorities) {
        this.authorities = authorities;
    }


    public void setEnabled(boolean enabled) {
        isEnabled = enabled;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getStatus() {
        return status;
    }

    public String getDisplayName() {
        return displayName;
    }

    public void setDisplayName(String displayName) {
        this.displayName = displayName;
    }

    public Map<String, String> getUserParamMap() {
        return userParamMap;
    }

    public void setUserParamMap(Map<String, String> userParamMap) {
        this.userParamMap = userParamMap;
    }

    @Override
    public Collection<GrantedAuthority> getAuthorities() {
        return authorities;
    }

    @Override
    public boolean isAccountNonExpired() {
        return isAccountNonExpired;
    }

    @Override
    public boolean isAccountNonLocked() {
        return isAccountNonLocked;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return isCredentialsNonExpired;
    }

    @Override
    public boolean isEnabled() {
        return isEnabled;
    }


}

六、編寫JWT接口請求攔截器

package com.springcloud.blog.admin.security.jwt;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.springcloud.blog.admin.config.JWTConfig;
import com.springcloud.blog.admin.security.entity.SelfUserEntity;
import com.springcloud.blog.admin.utils.CollectionUtil;
import com.springcloud.blog.admin.utils.JWTTokenUtil;
import com.springcloud.blog.admin.utils.RedisUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * JWT接口請求校驗攔截器
 * 請求接口時會進入這裏驗證Token是否合法和過期
 *
 * @Author youcong
 */
public class JWTAuthenticationTokenFilter extends BasicAuthenticationFilter {

    public JWTAuthenticationTokenFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 獲取請求頭中JWT的Token
        String tokenHeader = request.getHeader(JWTConfig.tokenHeader);

        if (null != tokenHeader && tokenHeader.startsWith(JWTConfig.tokenPrefix)) {
            try {


                // 截取JWT前綴
                String token = tokenHeader.replace(JWTConfig.tokenPrefix, "");
                // 解析JWT
                Claims claims = Jwts.parser()
                        .setSigningKey(JWTConfig.secret)
                        .parseClaimsJws(token)
                        .getBody();
                // 獲取用戶名
                String username = claims.getSubject();
                String userId = claims.getId();


                if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(userId)) {
                    // 獲取角色
                    List<GrantedAuthority> authorities = new ArrayList<>();
                    String authority = claims.get("authorities").toString();
                    if (!StringUtils.isEmpty(authority)) {
                        List<Map<String, String>> authorityMap = JSONObject.parseObject(authority, List.class);
                        for (Map<String, String> role : authorityMap) {
                            if (!StringUtils.isEmpty(role)) {
                                authorities.add(new SimpleGrantedAuthority(role.get("authority")));
                            }
                        }
                    }
                    //組裝參數
                    SelfUserEntity selfUserEntity = new SelfUserEntity();
                    selfUserEntity.setUsername(claims.getSubject());
                    selfUserEntity.setUserId(Long.parseLong(claims.getId()));
                    selfUserEntity.setAuthorities(authorities);
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(selfUserEntity, userId, authorities);
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            } catch (ExpiredJwtException e) {
                System.out.println("Token過期");
            } catch (Exception e) {
                System.out.println("Token無效");
            }
        }
        filterChain.doFilter(request, response);
        return;
    }
}

七、SpringSecurity用戶的業務實現

package com.springcloud.blog.admin.security.service;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.springcloud.blog.admin.entity.Users;
import com.springcloud.blog.admin.security.entity.SelfUserEntity;
import com.springcloud.blog.admin.service.UsersService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * SpringSecurity用戶的業務實現
 *
 * @Author youcong
 */
@Component
public class SelfUserDetailsService implements UserDetailsService {

    @Autowired
    private UsersService usersService;

    /**
     * 查詢用戶信息
     *
     * @Author youcong
     * @Param username  用戶名
     * @Return UserDetails SpringSecurity用戶信息
     */
    @Override
    public SelfUserEntity loadUserByUsername(String username) throws UsernameNotFoundException {

        EntityWrapper<Users> wrapper = new EntityWrapper<>();


        //郵箱正則表達式
        String expr = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})$";

        //是否為郵箱
        if (username.matches(expr)) {
            wrapper.eq("user_email", username);
        } else {
            wrapper.eq("user_login", username);
        }

        // 查詢用戶信息
        Users sysUserEntity = usersService.selectOne(wrapper);
        if (sysUserEntity != null) {
            // 組裝參數
            SelfUserEntity selfUserEntity = new SelfUserEntity();
            BeanUtils.copyProperties(sysUserEntity, selfUserEntity);
            return selfUserEntity;
        }
        return null;
    }
}

八、Spring Security常用註解

1.@Secured

當@EnableGlobalMethodSecurity(securedEnabled=true)的時候,@Secured可以使用。

@PostMapping("/helloUser")
@Secured({"ROLE_normal","ROLE_admin"})
public Map<String, Object> initDashboard() {
        Map<String, Object> result = new HashMap<>();
        result.put(ResponseDict.RESPONSE_TITLE_KEY, "儀錶盤初始化");
        result.put(ResponseDict.RESPONSE_DATA_KEY, dashboardService.initDashboard());
        return ResultUtil.resultSuccess(result);
    }

說明:擁有normal或者admin角色的用戶都可以方法helloUser()方法。另外需要注意的是這裏匹配的字符串需要添加前綴“ROLE_“。

2.@PreAuthorize

Spring的 @PreAuthorize/@PostAuthorize 註解更適合方法級的安全,也支持Spring 表達式語言,提供了基於表達式的訪問控制。

當@EnableGlobalMethodSecurity(prePostEnabled=true)的時候,@PreAuthorize可以使用:

@PostMapping("/initDashboard")
@PreAuthorize("hasRole('100')")
public Map<String, Object> initDashboard() {
    Map<String, Object> result = new HashMap<>();
    result.put(ResponseDict.RESPONSE_TITLE_KEY, "儀錶盤初始化");
    result.put(ResponseDict.RESPONSE_DATA_KEY, dashboardService.initDashboard());
    return ResultUtil.resultSuccess(result);
}

3.@PostAuthorize

@PostAuthorize 註解使用並不多,在方法執行后再進行權限驗證,適合驗證帶有返回值的權限,Spring EL 提供 返回對象能夠在表達式語言中獲取返回的對象returnObject。

當@EnableGlobalMethodSecurity(prePostEnabled=true)的時候,@PostAuthorize可以使用:

@GetMapping("/getUserInfo")
@PostAuthorize(" returnObject!=null &&  returnObject.username == authentication.name")
public User getUserInfo() {
        Object pricipal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User user;
        if("anonymousUser".equals(pricipal)) {
            user = null;
        }else {
            user = (User) pricipal;
        }
        return user;
}

九、測試

(1)登錄測試,拿到token,如圖:

 

 

(2)請求中如果不攜帶token的話,請求其它接口就會显示沒有登錄的提示,如圖:

 

 

(3)正確的請求應當攜帶token,就像下面這樣,如圖:

 

 

(4)沒有權限請求,如圖:

 

 

本站聲明:網站內容來源於博客園,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

※教你寫出一流的銷售文案?

※廣告預算用在刀口上,台北網頁設計公司幫您達到更多曝光效益

※回頭車貨運收費標準

※別再煩惱如何寫文案,掌握八大原則!

※超省錢租車方案

※產品缺大量曝光嗎?你需要的是一流包裝設計!

「從零單排canal 02」canal集群版 + admin控制台 最新搭建姿勢(基於1.1.4版本)

canal [kə’næl],譯意為水道/管道/溝渠,主要用途是基於 MySQL 數據庫增量日誌解析,提供增量數據 訂閱 和 消費。應該是阿里雲DTS(Data Transfer Service)的開源版本,開源地址:
https://github.com/alibaba/canal。

canal從1.1.4版本開始引入了admin控制台,有了很多不一樣的配置方式。在搭建過程中如果僅僅按照wiki的用戶手冊,還是容易踩很多坑的。因此,將筆者在搭建過程中的步驟記錄下來,作為官方wiki的 補充,希望能有所幫助。

根據本文內容與搭建順序 ,並搭配對應的官網文檔鏈接,應該就能快速搭建完成了,enjoy~

1. 部署canal-admin

1)部署服務

官方文檔地址:
https://github.com/alibaba/canal/wiki/Canal-Admin-QuickStart

主要配置application.yml文件

server:
  port: 8089

spring:
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8

spring.datasource:
  address: 127.0.0.1:3306
  database: canal_manager
  username: xxxx
  assword: xxxxx
  driver-class-name: com.mysql.jdbc.Driver
  url: jdbc:mysql://${spring.datasource.address}/${spring.datasource.database}?useUnicode=true&characterEncoding=UTF-8&useSSL=false
  hikari:
    maximum-pool-size: 30
    minimum-idle: 1

canal:
  adminUser: admin
  adminPasswd: admin

 

這裏需要注意,canal的adminPasswd並不是登陸admin的密碼,登陸admin的密碼是設置在對應的數據庫中的,默認為123456。

另外,因為 Canal Admin 是一個管理系統,需要使用數據庫存放配置信息,只用在 MySQL 中執行 Canal Admin 提供的數據庫初始化文件即可,該文件在“conf/canal_manager.sql”路徑下面。

2)登陸瀏覽器訪問

上面的 Canal Admin 配置好了之後直接根據“/bin/startup.sh”啟動 Canal Admin 即可,在瀏覽器上面輸入 hostip:8089 即可進入到管理頁面,如果使用的默認的配置信息,用戶名入”admin”,密碼輸入”123456”即可訪問首頁。

進入到首頁點擊集群的菜單欄,然後選擇新建集群。

在裏面輸入集群的名稱以及 Zookeeper即可,這裏的集群目前還沒有任務節點,後續通過配置 Canal Server 的自動註冊功能,便可以查看該集群下面擁有的節點。

創建集群后,需要先配置集群 主配置,載入模板即可。

如果沒有載入這個模版,那麼在canal-server執行 sh bin/startup.sh local 命令,讀取canal_local.propeties配置啟動時,會報錯

1 Caused by: com.alibaba.otter.canal.common.CanalException: requestGet for canal config error: canal.properties config is empty

 

注意,在主配置中,還是需要記得加入zk的地址配置,跟上面配置集群名字的時候輸入的zk無關 (那個zk地址不知道有啥用):

canal.zkServers = xxx.xx.xx.xx:2181,xxx.xx.xx.xx:2181,xxx.xx.xx.xx:2181

 

如果希望使用canal的集群模式(推薦使用),記得更改配置使用default-instance.xml,不要使用file-instance.xml配置,如下:

#canal.instance.global.spring.xml = classpath:spring/memory-instance.xml
#canal.instance.global.spring.xml = classpath:spring/file-instance.xml
canal.instance.global.spring.xml = classpath:spring/default-instance.xml

2. 部署canal-server

注意,建議先部署好admin,再來部署canal-server,省事不少。

官方文檔地址:
https://github.com/alibaba/canal/wiki/QuickStart

注意,不同於單機版的properties配置,使用admin后,各種配置通過admin全局管理,所以只需要配置canal_local.properties即可。canal_local.properties內容如下:

# register ip
canal.register.ip =

# canal admin config
canal.admin.manager = 127.0.0.1:8089
canal.admin.port = 11110
canal.admin.user = admin
canal.admin.passwd = xxxxxxxxxxxxxx

# admin auto register
canal.admin.register.auto = true
canal.admin.register.cluster =

 

對各個參數說明一下:

  • canal.register.ip:用來指定當前 Canal Server 的 IP 信息,如果主機是多網卡,可以避免 IP 信息錯亂的問題。
  • canal.admin.passwd:這裏的密碼就是之前配置 Canal Admin 裏面配置的adminPasswd,只不過這裏並不是明文展示,使用 MySQL 的”select password(“admin”)”語句查詢處理過的密碼,注意查詢結果前面的”*”要去掉。
  • canal.admin.register.auto:這裡是自動註冊的意思,如果沒有配置,Canal Server 啟動后需要自行在 Canal Admin 上面添加。
  • canal.admin.register.cluster:這個配置如果不寫代表當前的 Canal Server 是一個單機節點,如果添加的名字在 Canal Admin 上面沒有提前註冊,Canal Server 啟動時會報錯。

啟動server,切記切記帶上參數local,這樣才會讀取canal_local.properties的配置

sh bin/startup.sh local
啟動完成后,可以在admin界面看到server的連接信息

 

同時,登陸zk,查看是否已經註冊成功。

 

3. 配置canal-server

採用admin的集群模式后,集群內的canal-server通過zk做HA,因此,canal-server的配置也只能通過集群做全局配置。

就是前面的集群配置-主配置進入。

 

另外,canal作為一個增量數據抓取模塊,抓到變更信息后需要投遞。

通過canal.sererMode配置

這裏也限制了,一個集群內的canal只能支持一種投遞模式。

我們目前暫時以投遞RocketMQ為例進行配置。

官方文檔地址:
https://github.com/alibaba/canal/wiki/Canal-Kafka-RocketMQ-QuickStart

最終配置文件的配置如下:

#################################################
#########         common argument        #############
#################################################

# tcp bind ip
canal.ip =

# register ip to zookeeper
canal.register.ip =
canal.port = 11111
canal.metrics.pull.port = 11112

# canal instance user/passwd
canal.user = xxxx
canal.passwd = xxxxxxxxxxxxxxxxxxx

# canal admin config
canal.admin.manager = 127.0.0.1:8089
canal.admin.port = 11110
canal.admin.user = xxxx
canal.admin.passwd = xxxxxxxxxxxxxx
canal.zkServers = xx.xx.xx.xx:xxxx,xx.xx.xx.xxx:xxxx,xx.xx.xx.xx:xxxx

# flush data to zk
canal.zookeeper.flush.period = 1000
canal.withoutNetty = false

# tcp, kafka, RocketMQ
canal.serverMode = RocketMQ

# flush meta cursor/parse position to file
canal.file.data.dir = ${canal.conf.dir}
canal.file.flush.period = 1000

## memory store RingBuffer size, should be Math.pow(2,n)
canal.instance.memory.buffer.size = 16384

## memory store RingBuffer used memory unit size , default 1kb
canal.instance.memory.buffer.memunit = 1024

## meory store gets mode used MEMSIZE or ITEMSIZE
canal.instance.memory.batch.mode = MEMSIZE
canal.instance.memory.rawEntry = true

## detecing config
canal.instance.detecting.enable = false

#canal.instance.detecting.sql = insert into retl.xdual values(1,now()) on duplicate key update x=now()
canal.instance.detecting.sql = select 1
canal.instance.detecting.interval.time = 3
canal.instance.detecting.retry.threshold = 3
canal.instance.detecting.heartbeatHaEnable = false

# support maximum transaction size, more than the size of the transaction will be cut into multiple transactions delivery
canal.instance.transaction.size =  1024

# mysql fallback connected to new master should fallback times
canal.instance.fallbackIntervalInSeconds = 60

# network config
canal.instance.network.receiveBufferSize = 16384
canal.instance.network.sendBufferSize = 16384
canal.instance.network.soTimeout = 30

# binlog filter config
# 這裏可以對訂閱的消息做過濾
canal.instance.filter.druid.ddl = true
canal.instance.filter.query.dcl = false
canal.instance.filter.query.dml = false
canal.instance.filter.query.ddl = false
canal.instance.filter.table.error = false
canal.instance.filter.rows = false
canal.instance.filter.transaction.entry = false

# binlog format/image check
canal.instance.binlog.format = ROW,STATEMENT,MIXED
canal.instance.binlog.image = FULL,MINIMAL,NOBLOB

# binlog ddl isolation
canal.instance.get.ddl.isolation = false

# parallel parser config
canal.instance.parser.parallel = true

## concurrent thread number, default 60% available processors, suggest not to exceed Runtime.getRuntime().availableProcessors()
#canal.instance.parser.parallelThreadSize = 16
## disruptor ringbuffer size, must be power of 2
canal.instance.parser.parallelBufferSize = 256

# table meta tsdb info
canal.instance.tsdb.enable = true
canal.instance.tsdb.dir = ${canal.file.data.dir:../conf}/${canal.instance.destination:}
canal.instance.tsdb.url = jdbc:h2:${canal.instance.tsdb.dir}/h2;CACHE_SIZE=1000;MODE=MYSQL;
canal.instance.tsdb.dbUsername = canal
canal.instance.tsdb.dbPassword = canal

# dump snapshot interval, default 24 hour
canal.instance.tsdb.snapshot.interval = 24

# purge snapshot expire , default 360 hour(15 days)
canal.instance.tsdb.snapshot.expire = 360

# aliyun ak/sk , support rds/mq
canal.aliyun.accessKey =
canal.aliyun.secretKey =

#################################################
#########         destinations        #############
#################################################
canal.destinations =

# conf root dir
canal.conf.dir = ../conf

# auto scan instance dir add/remove and start/stop instance
canal.auto.scan = true
canal.auto.scan.interval = 5
canal.instance.tsdb.spring.xml = classpath:spring/tsdb/h2-tsdb.xml

#canal.instance.tsdb.spring.xml = classpath:spring/tsdb/mysql-tsdb.xml
canal.instance.global.mode = manager
canal.instance.global.lazy = false
canal.instance.global.manager.address = ${canal.admin.manager}

#canal.instance.global.spring.xml = classpath:spring/memory-instance.xml

#canal.instance.global.spring.xml = classpath:spring/file-instance.xml
canal.instance.global.spring.xml = classpath:spring/default-instance.xml

##################################################
#########              MQ              #############
##################################################
canal.mq.servers = xx.xx.xx.xx:xxxx,xx.xx.xx.xxx:xxxx,xx.xx.xx.xx:xxxx
canal.mq.retries = 0
canal.mq.canalBatchSize = 50
canal.mq.canalGetTimeout = 100
canal.mq.flatMessage = true
canal.mq.compressionType = none
canal.mq.acks = all

#canal.mq.properties. =
canal.mq.producerGroup = test_canal_cluster

# Set this value to "cloud", if you want open message trace feature in aliyun.
canal.mq.accessChannel = local

# aliyun mq namespace

#canal.mq.namespace =

##################################################
#########     Kafka Kerberos Info    #############
##################################################
canal.mq.kafka.kerberos.enable = false
canal.mq.kafka.kerberos.krb5FilePath = "../conf/kerberos/krb5.conf"
canal.mq.kafka.kerberos.jaasFilePath = "../conf/kerberos/jaas.conf"

 

4. 配置canal instance(以投遞MQ為例)

Canal Admin 提供了 Canal Instance 的管理功能。

我們嘗試通過 UI 界面添加需要監聽的數據庫,讓該 Instance 消費 binlog 並將事件發送到 MQ。

  • 點擊“新建 Instance”按鈕創建 Instance
  • 點擊“載入模板”,進行配置修改。

主要修改以下配置:

  • ”canal.instance.mysql.slaveId”:目前1.1.4版本已經不需要配置,系統自動生成
  • ”canal.instance.master.address”:配置你的數據庫地址
  • canal.instance.dbUsername:數據庫用戶名
  • canal.instance.dbPassword:數據庫密碼
  • canal.mq.topic:mq的topic
  • canal.instance.filter.regex=訂閱的庫表名單(例如:dbvtest\\..*),具體參考https://github.com/alibaba/canal/wiki/AdminGuide

保存,啟動,觀察日誌,沒有報錯即可。

同時可以從 canal-server的 操作-詳情 進入,查看可以看到正在運行的instance

這裏需要注意,如果沒有正確註冊到zk,那麼每個canal-server都會有一個正在運行的instance,會導致變更投遞多次。

如果正確註冊了zk,同一個集群下,每個instance應該只在某一個cannal-server中運行。

可以查看zk路徑

/otter/canal/destinations/{xxxx}/running

 

xxxx就是instance的 名稱,running節點表示它運行在哪個server上。

另外,目前對binlog的訂閱支持gtid模式和position模式,通過以下參數設置

# enable gtid use true/false
canal.instance.gtidon=false

 

在demo過程中,發現高可用模式下,gtid無法正常更新到zk,而position模式使用正常。

gtid模式在canal高可用模式下可能存在bug(參考issue:
https://github.com/alibaba/canal/issues/2616),暫時不建議使用。

5. 演練訂閱

在rds執行以下sql

UPDATE `album` SET `attribute`=’5′ WHERE `albumid`=’1′;

在MQ中的消息格式如下:

{

    "data":[

        {
            "albumid":"1",
            "picid":"1234",
            "attribute":"5",
            "lastmodified":"2020-05-15 18:13:35",
            "created":"2019-09-04 18:18:51"
        }
    ],
    "database":"dbvtest",
    "es":1589537615000,
    "id":75,
    "isDdl":false,
    "mysqlType":{
        "albumid":"int(10) unsigned",
        "picid":"int(10) unsigned",
        "attribute":"varchar(200)",
        "lastmodified":"timestamp",
        "created":"timestamp"
    },
    "old":[
        {
            "attribute":"2",
            "lastmodified":"2020-05-15 17:42:57"
        }
    ],
    "pkNames":[
        "albumid"
    ],
    "sql":"",
    "sqlType":{
        "albumid":4,
        "picid":4,
        "attribute":12,
        "lastmodified":93,
        "created":93
    },
    "table":"album",
    "ts":1589537615877,
    "type":"UPDATE"
}

 

6. 監控告警

官方文檔地址:
https://github.com/alibaba/canal/wiki/Prometheus-QuickStart

如果你已經有一套prometheus的監控體系,我們只需要導入模板(
canal/conf/metrics/Canal_instances_tmpl.json)即可,完美~

 

都看到最後了,原創不易,點個關注,點個贊吧~

知識碎片重新梳理,構建Java知識圖譜: github.com/saigu/JavaK…(歷史文章查閱非常方便)

本站聲明:網站內容來源於博客園,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

※超省錢租車方案

※別再煩惱如何寫文案,掌握八大原則!

※回頭車貨運收費標準

※教你寫出一流的銷售文案?

※產品缺大量曝光嗎?你需要的是一流包裝設計!

※廣告預算用在刀口上,台北網頁設計公司幫您達到更多曝光效益

11萬就能買到舒適性堪比天籟的SUV 你覺得值不值

T90最大的賣點來了,都說自主品牌的動力系統調教的不好,T90直接使用了日產MR20的2。0L自然吸氣發動機,最大功率144馬力,最大扭矩198牛·米,匹配CVT變速箱(低配為6擋手動)。這套動力系統目前也用在天籟和逍客上面搭載,看到這些,你還會擔心T90的動力系統么。

12月25日晚上,東風日產啟辰中型SUV—T90正式上市,價格區間為10.98-15.48萬元。

T90也是小編比較期待的一款自主中型SUV,因為此車有着時尚的外觀,精緻的內飾,舒適的座椅,同時和日產有着千絲萬縷的聯繫,所以小編一直很關注它,直到看到它的正式售價,心裏的石頭也終於落地了,畢竟在價格上,啟辰沒有“逗我們玩”。

T90定位中型轎跑型SUV,目前是啟辰的旗艦車型。T90的車身尺寸為4793*1865*1592mm(不同車型高度略有差異),軸距為2765mm,身材在同級別車型處於正常水準。T90的外觀和寶馬X6、歌詩圖有點類似,都是有着溜背的造型,再加上車子較長,所以T90的側面看起來非常的修長,惹人喜愛。

T90的設計理念為“風雕美學”,這是啟辰第一次運用這個理念設計出來的車型,所以T90的整體外觀看起來會使人眼前一亮,同時別緻的前進氣格柵也為T90加分不少。

內飾也是很討人喜歡的地方,中控台都採用了軟性材質覆蓋,摸起來很柔軟,手感很好,同時做工也比較精細,看得出裝配工藝還是很嚴格的。中控台採用了分辨率高達1920*768的12.3英寸的大屏幕,不僅大氣,同時畫面也比較清晰,運行很流暢,客戶體驗效果很好。

座椅也是T90的亮點,因為T90的尺寸足夠大,所以它的內部空間還是非常寬敞的,尤其是T90採用了和天籟同級別的人體工程學座椅,而移動大沙發是天籟的綽號,所以T90座椅的舒適程度可想而知了。不過遺憾的就是溜背的造型會犧牲一定的後排頭部空間,那些大個子乘客可能要盡量坐到前排了。

T90最大的賣點來了,都說自主品牌的動力系統調教的不好,T90直接使用了日產MR20的2.0L自然吸氣發動機,最大功率144馬力,最大扭矩198牛·米,匹配CVT變速箱(低配為6擋手動)。這套動力系統目前也用在天籟和逍客上面搭載,看到這些,你還會擔心T90的動力系統么?

說了這麼多,大家一定會說T90哪款車的性價比最高了。除了低配和頂配兩款車,T90的同一級別車型的自動和手動車型差價一萬元,相當於多花10000元買一台CVT變速箱,這個價格在同級別屬於正常水平。

其中最低配手動辰尚版配備了主/副駕氣囊、無鑰匙啟動/進入、剎車輔助、多功能方向盤、中控大屏、藍牙電話、後座出風口,配置比較實用,基本可以滿足日常行車需求。唯一遺憾的就是沒有ESp。

手動風尚版和手動辰尚版差價8000元,但是只是多了這兩個配置,性價比較低。而CVT風尚版比手動風尚版貴10000元,多了CVT變速箱,這也可以得出CVT風尚版的性價比也是比較低的。

智尚版僅僅比風尚版貴8000元,但是卻多了這麼多的配置,不得不說性價比真的很高。

頂配CVT領尚版比次頂配CVT智尚版貴1.9萬元,但是只是多了后駐車雷達、腰部支撐調節、前排座椅加熱、LED近光燈、車內氛圍燈、併線輔助、全景攝像頭和更大的輪轂,總體來看性價比並不高。

如果資金不充足,最低配手動辰尚版性價比非常高,如果想要一些配置,那麼智尚版的性價比非常高。總體來說啟辰的質量口碑很好,在加上T90和日產的關係,所以T90也是一款不錯的車型,不過受制於啟辰的知名度限制,能不能熱銷,還是要看T90的造化了。本站聲明:網站內容來源於http://www.auto6s.com/,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

※帶您來了解什麼是 USB CONNECTOR  ?

※自行創業缺乏曝光? 網頁設計幫您第一時間規劃公司的形象門面

※如何讓商品強力曝光呢? 網頁設計公司幫您建置最吸引人的網站,提高曝光率!

※綠能、環保無空污,成為電動車最新代名詞,目前市場使用率逐漸普及化

※廣告預算用在刀口上,台北網頁設計公司幫您達到更多曝光效益

※教你寫出一流的銷售文案?