為什么要用SpringBoot?
創(chuàng)新互聯(lián)建站是創(chuàng)新、創(chuàng)意、研發(fā)型一體的綜合型網(wǎng)站建設(shè)公司,自成立以來公司不斷探索創(chuàng)新,始終堅持為客戶提供滿意周到的服務(wù),在本地打下了良好的口碑,在過去的10年時間我們累計服務(wù)了上千家以及全國政企客戶,如成都展覽展示等企業(yè)單位,完善的項目管理流程,嚴(yán)格把控項目進度與質(zhì)量監(jiān)控加上過硬的技術(shù)實力獲得客戶的一致夸獎。
SpringBoot是由Pivotal團隊提供的全新框架,其設(shè)計目的是用來簡化新Spring應(yīng)用的初始搭建以及開發(fā)過程。該框架使用了特定的方式來進行配置,從而使開發(fā)人員不再需要定義樣板化的配置。通過這種方式,Spring Boot致力于在蓬勃發(fā)展的快速應(yīng)用開發(fā)領(lǐng)域(rapid application development)成為領(lǐng)導(dǎo)者。
為什么要用Nginx?
概述
Nginx(engine x)是一個開源的,支持高并發(fā)的www服務(wù)和代理服務(wù)軟件。Nginx是俄羅斯人Igor Sysoev開發(fā)的,最初被應(yīng)用到俄羅斯的大型網(wǎng)站(www.rambler.ru)上。后來作者將源代碼以類BSD許可證的形式開源出來供全球使用。在功能應(yīng)用方面,Nginx不僅是一個優(yōu)秀的Web服務(wù)軟件,還具有反向代理負(fù)載均衡和緩存的功能。在反向代理負(fù)載均衡方面類似于LVS負(fù)載均衡及HAProxy等你專業(yè)代理軟件。Nginx部署起來更加方便簡單,在緩存服務(wù)功能方面,有類似于Squid等專業(yè)的緩存服務(wù)軟件。Nginx可以運行在UNIX、Linux、MS Windows Server、Mac OS X Server、Solaris等操作系統(tǒng)中。
Nginx的重要特性
Nginx所具備的WWW服務(wù)特性
Nginx軟件主要企業(yè)應(yīng)用
Web服務(wù)應(yīng)用產(chǎn)品性能對比
為什么Nginx比Apache的性能高?
如何正確采用Web服務(wù)器?
關(guān)于部署,就不在重復(fù)了,如果需要請移步《Java高級架構(gòu)之FastDFS分布式文件集群》:
使用IDEA場景啟動器創(chuàng)建工程
創(chuàng)建Maven工程,修改POM.xml文件添加如下依賴:
org.springframework.boot spring-boot-autoconfigure 1.5.20.RELEASE org.springframework.boot spring-boot-configuration-processor 1.5.20.RELEASE org.springframework.boot spring-boot-starter-logging 1.5.20.RELEASE org.apache.commons commons-pool2 2.6.0
創(chuàng)建必要的包
一般情況下,SpringBoot都會提供相應(yīng)的@EnableXxx注解標(biāo)注在應(yīng)用的主啟動類上開啟某個功能:
// EnableFastdfsClient.java @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Import(FastdfsAutoConfiguration.class) @Documented public @interface EnableFastdfsClient { }
下面是相關(guān)的自動配置類:
// FastdfsAutoConfiguration.java @Configuration @EnableConfigurationProperties(FastdfsProperties.class) public class FastdfsAutoConfiguration { @Autowired private FastdfsProperties fastdfsProperties; @Bean @ConditionalOnMissingBean(FastdfsClientService.class) public FastdfsClientService fastdfsClientService() throws Exception { return new FastdfsClientService(fastdfsProperties); } }
創(chuàng)建相關(guān)的工廠類:
// StorageClientFactory.java // 用于創(chuàng)建連接對象的工廠類 public class StorageClientFactory implements PooledObjectFactory{ @Override public PooledObject makeObject() throws Exception { TrackerClient client = new TrackerClient(); TrackerServer server = client.getConnection(); return new DefaultPooledObject<>(new StorageClient(server, null)); } @Override public void destroyObject(PooledObject p) throws Exception { p.getObject().getTrackerServer().close(); } @Override public boolean validateObject(PooledObject p) { return false; } @Override public void activateObject(PooledObject p) throws Exception { } @Override public void passivateObject(PooledObject p) throws Exception { } }
Properties類用來映射application.properties或者application.yml配置文件:
// FastdfsProperties.java @ConfigurationProperties(prefix = "fastdfs") public class FastdfsProperties { // 連接超時時間 // 網(wǎng)絡(luò)超時時間 // 字符集編碼 // 是否使用Token // Token加密密鑰 // 跟蹤器IP地址,多個使用分號隔開 // 連接池的連接對象最大個數(shù) // 連接池的最大空閑對象個數(shù) // 連接池的最小空閑對象個數(shù) // Nginx服務(wù)器IP,多個使用分號分割 // 獲取連接對象時可忍受的等待時長(毫秒) private String connectTimeout = "5"; private String networkTimeout = "30"; private String charset = "UTF-8"; private String httpAntiStealToken = "false"; private String httpSecretKey = ""; private String httpTrackerHttpPort = ""; private String trackerServers = ""; private String connectionPoolMaxTotal = "18"; private String connectionPoolMaxIdle = "18"; private String connectionPoolMinIdle = "2"; private String nginxServers = ""; // 需要創(chuàng)建相關(guān)的Setter和Getter方法 }
在Service類中封裝方法, 下面僅展示3個常用的方法:
// FastdfsClientSerivce.java public class FastdfsClientService { // SpringBoot加載的配置文件 // 連接池配置項 // 轉(zhuǎn)換后的配置條目 // 連接池 // Nginx服務(wù)器地址 private FastdfsProperties fdfsProp; private GenericObjectPoolConfig config; private Properties prop; private GenericObjectPoolpool; private String[] nginxServers; private Logger logger; public FastdfsClientService(FastdfsProperties fdfsProp) throws Exception { this.fdfsProp = fdfsProp; this.logger = LoggerFactory.getLogger(getClass()); init(); create(); info(); } /** * 初始化全局客戶端 */ private void init() throws Exception { this.prop = new Properties(); this.logger.info("FastDFS: reading config file..."); this.logger.info("FastDFS: fastdfs.connect_timeout_in_seconds=" + this.fdfsProp.getConnectTimeout()); this.logger.info("FastDFS: fastdfs.network_timeout_in_seconds=" + this.fdfsProp.getNetworkTimeout()); this.logger.info("FastDFS: fastdfs.charset=" + this.fdfsProp.getCharset()); this.logger.info("FastDFS: fastdfs.http_anti_steal_token=" + this.fdfsProp.getHttpAntiStealToken()); this.logger.info("FastDFS: fastdfs.http_secret_key=" + this.fdfsProp.getHttpSecretKey()); this.logger.info("FastDFS: fastdfs.http_tracker_http_port=" + this.fdfsProp.getHttpTrackerHttpPort()); this.logger.info("FastDFS: fastdfs.tracker_servers=" + this.fdfsProp.getTrackerServers()); this.logger.info("FastDFS: fastdfs.connection_pool_max_total=" + this.fdfsProp.getConnectionPoolMaxTotal()); this.logger.info("FastDFS: fastdfs.connection_pool_max_idle=" + this.fdfsProp.getConnectionPoolMaxIdle()); this.logger.info("FastDFS: fastdfs.connection_pool_min_idle=" + this.fdfsProp.getConnectionPoolMinIdle()); this.logger.info("FastDFS: fastdfs.nginx_servers=" + this.fdfsProp.getNginxServers()); this.prop.put("fastdfs.connect_timeout_in_seconds", this.fdfsProp.getConnectTimeout()); this.prop.put("fastdfs.network_timeout_in_seconds", this.fdfsProp.getNetworkTimeout()); this.prop.put("fastdfs.charset", this.fdfsProp.getCharset()); this.prop.put("fastdfs.http_anti_steal_token", this.fdfsProp.getHttpAntiStealToken()); this.prop.put("fastdfs.http_secret_key", this.fdfsProp.getHttpSecretKey()); this.prop.put("fastdfs.http_tracker_http_port", this.fdfsProp.getHttpTrackerHttpPort()); this.prop.put("fastdfs.tracker_servers", this.fdfsProp.getTrackerServers()); ClientGlobal.initByProperties(this.prop); } /** * 顯示初始化信息 */ private void info() { this.logger.info("FastDFS parameter: ConnectionPoolMaxTotal ==> " + this.pool.getMaxTotal()); this.logger.info("FastDFS parameter: ConnectionPoolMaxIdle ==> " + this.pool.getMaxIdle()); this.logger.info("FastDFS parameter: ConnectionPoolMinIdle ==> " + this.pool.getMinIdle()); this.logger.info("FastDFS parameter: NginxServer ==> " + Arrays.toString(this.nginxServers)); this.logger.info(ClientGlobal.configInfo()); } /** * 創(chuàng)建連接池 */ private void create() { this.config = new GenericObjectPoolConfig(); this.logger.info("FastDFS Client: Creating connection pool..."); this.config.setMaxTotal(Integer.parseInt(this.fdfsProp.getConnectionPoolMaxTotal())); this.config.setMaxIdle(Integer.parseInt(this.fdfsProp.getConnectionPoolMaxIdle())); this.config.setMinIdle(Integer.parseInt(this.fdfsProp.getConnectionPoolMinIdle())); StorageClientFactory factory = new StorageClientFactory(); this.pool = new GenericObjectPool (factory, this.config); this.nginxServers = this.fdfsProp.getNginxServers().split(","); } /** * Nginx服務(wù)器負(fù)載均衡算法 * * @param servers 服務(wù)器地址 * @param address 客戶端IP地址 * @return 可用的服務(wù)器地址 */ private String getNginxServer(String[] servers, String address) { int size = servers.length; int i = address.hashCode(); int index = abs(i % size); return servers[index]; } /** * 帶有防盜鏈的下載 * * @param fileGroup 文件組名 * @param remoteFileName 遠(yuǎn)程文件名稱 * @param clientIpAddress 客戶端IP地址 * @return 完整的URL地址 */ public String autoDownloadWithToken(String fileGroup, String remoteFileName, String clientIpAddress) throws Exception { int ts = (int) (System.currentTimeMillis() / 1000); String token = ProtoCommon.getToken(remoteFileName, ts, ClientGlobal.getG_secret_key()); String nginx = this.getNginxServer(this.nginxServers, clientIpAddress); return "http://" + nginx + "/" + fileGroup + "/" + remoteFileName + "?token=" + token + "&ts=" + ts; } /** * 上傳文件,適合上傳圖片 * * @param buffer 字節(jié)數(shù)組 * @param ext 擴展名 * @return 文件組名和ID */ public String[] autoUpload(byte[] buffer, String ext) throws Exception { String[] upload = this.upload(buffer, ext, null); return upload; } /** * 不帶防盜鏈的下載,如果開啟防盜鏈會導(dǎo)致該方法拋出異常 * * @param fileGroup 文件組名 * @param remoteFileName 遠(yuǎn)程文件ID * @param clientIpAddress 客戶端IP地址,根據(jù)客戶端IP來分配Nginx服務(wù)器 * @return 完整的URL地址 */ public String autoDownloadWithoutToken(String fileGroup, String remoteFileName, String clientIpAddress) throws Exception { if (ClientGlobal.getG_anti_steal_token()) { this.logger.error("FastDFS Client: You've turned on Token authentication."); throw new Exception("You've turned on Token authentication."); } String nginx = this.getNginxServer(this.nginxServers, clientIpAddress); return "http://" + nginx + fileGroup + "/" + remoteFileName; } // 后面還有好多方法,就不一一展示了 }
為了在IDEA中使用便捷的配置提示功能,我們需要創(chuàng)建元數(shù)據(jù)文件(resources/spring-configuration-metadata.json):
{ "groups": [ { "name": "fastdfs", "type": "com.bluemiaomiao.properties.FastdfsProperties", "sourceType": "com.bluemiaomiao.properties.FastdfsProperties" } ], "properties": [ { "name": "connectTimeout", "type": "java.lang.String", "sourceType": "com.bluemiaomiao.properties.FastdfsProperties", "defaultValue": "5" }, { "name": "networkTimeout", "type": "java.lang.String", "sourceType": "com.bluemiaomiao.properties.FastdfsProperties", "defaultValue": "30" }, { "name": "charset", "type": "java.lang.String", "defaultValue": "UTF-8" }, { "name": "httpAntiStealToken", "type": "java.lang.String", "sourceType": "com.bluemiaomiao.properties.FastdfsProperties", "defaultValue": "false" }, { "name": "httpSecretKey", "type": "java.lang.String", "sourceType": "com.bluemiaomiao.properties.FastdfsProperties" }, { "name": "httpTrackerHttpPort", "type": "java.lang.Integer", "sourceType": "com.bluemiaomiao.properties.FastdfsProperties" }, { "name": "trackerServers", "type": "java.lang.String", "sourceType": "com.bluemiaomiao.properties.FastdfsProperties" }, { "name": "connectionPoolMaxTotal", "type": "java.lang.Integer", "sourceType": "com.bluemiaomiao.properties.FastdfsProperties", "defaultValue": "18" }, { "name": "connectionPoolMaxIdle", "type": "java.lang.Integer", "sourceType": "com.bluemiaomiao.properties.FastdfsProperties", "defaultValue": "18" }, { "name": "connectionPoolMinIdle", "type": "java.lang.Integer", "sourceType": "com.bluemiaomiao.properties.FastdfsProperties", "defaultValue": "2" }, { "name": "nginxServers", "type": "java.lang.String", "sourceType": "com.bluemiaomiao.properties.FastdfsProperties" } ], "hints": [ { "name": "http_anti_steal_token", "values": [ { "value": "false" }, { "value": "true" } ] } ] }
應(yīng)用到項目中
創(chuàng)建SpringBoot項目,勾選Web選項,版本選擇1.5.20
進入場景啟動器的項目目錄執(zhí)行mvn clean install 將其安裝到本地
在POM.xml文件中添加依賴:
com.bluemiaomiao fastdfs-spring-boot-starter 1.0-SNAPSHOT
記得開啟IDEA的自動導(dǎo)入功能
創(chuàng)建配置文件application.properties
fastdfs.nginx-servers=192.168.80.2:8000,192.168.80.3:8000,192.168.80.4:8000 fastdfs.tracker-servers=192.168.80.2:22122,192.168.80.3:22122,192.168.80.4:22122 fastdfs.http-secret-key=2scPwMPctXhbLVOYB0jyuyQzytOofmFCBIYe65n56PPYVWrntxzLIDbPdvDDLJM8QHhKxSGWTcr+9VdG3yptkw fastdfs.http-anti-steal-token=true fastdfs.http-tracker-http-port=8080 fastdfs.network-timeout=30 fastdfs.connect-timeout=5 fastdfs.connection-pool-max-idle=18 fastdfs.connection-pool-min-idle=2 fastdfs.connection-pool-max-total=18 fastdfs.charset=UTF-8
或者使用application.yml
fastdfs: charset: UTF-8 connect-timeout: 5 http-secret-key: 2scPwMPctXhbLVOYB0jyuyQzytOofmFCBIYe65n56PPYVWrntxzLIDbPdvDDLJM8QHhKxSGWTcr+9VdG3yptkw network-timeout: 30 http-anti-steal-token: true http-tracker-http-port: 8080 connection-pool-max-idle: 20 connection-pool-max-total: 20 connection-pool-min-idle: 2 nginx-servers: 192.168.80.2:8000,192.168.80.3:8000,192.168.80.4:8000 tracker-servers: 192.168.80.2:22122,192.168.80.3:22122,192.168.80.4:22122
創(chuàng)建控制器類測試方法
// controllers.DownloadController.java @Controller @RequestMapping(value = "/download") public class DownloadController { @Autowired private FastdfsClientService service; @ResponseBody @RequestMapping(value = "/image") public String image() throws Exception { // 之前上傳過的數(shù)據(jù),實際應(yīng)用場景應(yīng)該使用SQL數(shù)據(jù)庫來存儲 return service.autoDownloadWithToken("group1", "M00/00/00/wKhQA1ysjSGAPjXbAAVFOL7FJU4.tar.gz", "192.168.80.1"); } }
項目主頁:https://github.com/bluemiaomiao/fastdfs-spring-boot-starter
國內(nèi)項目主頁:https://gitee.com/bluemiaomiao/fastdfs-spring-boot-starter
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。