Giter VIP home page Giter VIP logo

spring-boot's Introduction

spring-boot

整理全部有關 Spring boot 的技術

切換環境設定

啟動圖片

spring boot 排程

  • Spring Boot Scheduling Tasks
  • 需要加 @EnableScheduling
  • https://polinwei.com/spring-boot-scheduling-tasks/
  • cron表示式定義
      ┌───────────── second (0-59)
      │ ┌───────────── minute (0 - 59)
      │ │ ┌───────────── hour (0 - 23)
      │ │ │ ┌───────────── day of the month (1 - 31)
      │ │ │ │ ┌───────────── month (1 - 12) (or JAN-DEC)
      │ │ │ │ │ ┌───────────── day of the week (0 - 7)
      │ │ │ │ │ │          (0 or 7 is Sunday, or MON-SUN)
      │ │ │ │ │ │
      * * * * * *
    
  • 可出現的字元型別和各字元的含義
     秒:可出現: ”, – * /” 左列的四個字元,有效範圍為0-59的整數
     分:可出現: ”, – * /” 左列的四個字元,有效範圍為0-59的整數
     時:可出現: ”, – * /” 左列的四個字元,有效範圍為0-23的整數
     每月第幾天:可出現: ”, – * / ? L W C” 左列的八個字元,有效範圍為0-31的整數
     月:可出現: ”, – * /” 左列的四個字元,有效範圍為1-12的整數或JAN-DEc
     星期:可出現: ”, – * / ? L C #” 左列的八個字元,有效範圍為1-7的整數或SUN-SAT兩個範圍。1表示星期天,2表示星期一, 依次類
    
  • 特殊字元含義
     * : 表示匹配該域的任意值,比如在秒*, 就表示每秒都會觸發事件。;
     ? : 只能用在每月第幾天和星期兩個域。表示不指定值,當2個子表示式其中之一被指定了值以後,為了避免衝突,需要將另一個子表示式的值設為“?”;
     – : 表示範圍,例如在分域使用5-20,表示從5分到20分鐘每分鐘觸發一次  
     / : 表示起始時間開始觸發,然後每隔固定時間觸發一次,例如在分域使用5/20,則意味著5分,25分,45分,分別觸發一次.  
     , : 表示列出列舉值。例如:在分域使用5,20,則意味著在5和20分時觸發一次。  
     L : 表示最後,只能出現在星期和每月第幾天域,如果在星期域使用1L,意味著在最後的一個星期日觸發。  
     W : 表示有效工作日(週一到週五),只能出現在每月第幾日域,系統將在離指定日期的最近的有效工作日觸發事件。注意一點,W的最近尋找不會跨過月份  
     LW : 這兩個字元可以連用,表示在某個月最後一個工作日,即最後一個星期五。  
     # : 用於確定每個月第幾個星期幾,只能出現在每月第幾天域。例如在1#3,表示某月的第三個星期日。
    

動態排程

filter

  • 使用 @Configuration、@Component
    • 預設為全部 api 皆會通過此 filter
  • 使用 @WebFilter
    • 指定特定 req 才會通過此 filter
    • 需要再新增 @ServletComponentScan 在 application.java 檔

使用 filter 紀錄 request 參數

使用 filter 紀錄 response 參數

  • 需要執行下列程式,否則會陷入 doFilter 的 loop
      ServletOutputStream outputStream = response.getOutputStream();
      outputStream.write(resbody.getBytes());
      outputStream.flush();
      outputStream.close();
    
  • https://blog.51cto.com/u_15585381/5277668

HandlerInterceptor (攔截器)

ApplicationContextAware (取得 spring bean)

Spring Actuator

  • 可以用來查看當前的 SpringBoot 程式運行的內部狀況,譬如知道自動化配置的資訊、創建的 Spring beans 和獲取當前的 properties 屬性值
    • 開啟所有endpoints(不包含shutdown)
      • management.endpoints.web.exposure.include=*
    • 開啟/actuator/beans和/actuator/mappings
      • management.endpoints.web.exposure.include=beans,mappings
  • 輸入 ./actuator/beans
  • https://kucw.github.io/blog/2020/7/spring-actuator/
  • 在 log 輸出部分,有紀錄
    Exposing 13 endpoint(s) beneath base path '/actuator'
    
  • 在 /actuator 裏面,常見的功能有:
    • beans:查詢全部被註冊 bean 的名稱
    • envs:查詢全部的環境變數 (包含自定義)
    • mappings:查看全部的 endpoint
    • scheduledtasks: 查看目前排程狀態

AnnotationBeanNameGenerator (註冊 spring bean 名稱)

  • 進行改寫 spring bean 名稱
  • 繼承 AnnotationBeanNameGenerator 並改寫 buildDefaultBeanName
  • 在啟動程式 (xxxApplication.class),@ComponentScan 需添加 nameGenerator 的參數

讀取 application.yml 檔內容

啟動時,自動執行 sql

jwt 範例

session 應用

  • 將資訊儲放 session 中
  • 從 HttpServletRequest 取出 session
  • 內部可以擺放物件
  • 登入時,存入 session ,登出時,清除 session
  • 在 application 內設定參數,可以修改 cookie 的名稱
    • server.servlet.session.cookie.name=COOKIE_NAME
  • https://springhow.com/customizing-spring-session-cookies/

上傳圖片與開啟圖片

建立 h2 db 可用 dbeaver 連線

  • h2 dependency 不需要使用 runtime

  • 新增一個 bean port 不可以和 spring 啟動的 port 一樣

     /**
       * Start internal H2 server so we can query the DB from IDE
       *
       * @return H2 Server instance
       * @throws SQLException
       */
      @Bean(initMethod = "start", destroyMethod = "stop")
      public Server h2Server() throws SQLException {
          return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", "9090");
      }
    
  • application.yml 設定

    spring:
    h2:
      console:
        enabled: true
        path: '/h2-console-log'
    
    datasource:
      url: 'jdbc:h2:mem:local'
    
  • dbeaver 使用 h2 server 連線

    • 組合資訊:bean 的 port + url h2 後面那一段
    • Host
    • jdbc:h2:tcp://localhost:9090/mem:local
  • https://stackoverflow.com/questions/43256295/how-to-access-in-memory-h2-database-of-one-spring-boot-application-from-another/43276769#43276769

swagger 設定

db table 設定

  • spring.jpa.hibernate.ddl-auto
    • create: 啟動時建立Table, 下次啟動會覆蓋上次的, 故會造成資料遺失
    • update: 若無Table則啟動時建立, 若有則視有無變更自動Update
    • create-drop: 啟動時建立Table, 當次Session關閉則刪除 (hsqldb, h2 的 default)
    • validate: 只驗證,不修改表格
    • none: 蛤也不做 (大部分的 default)
  • https://fookwood.com/hibernate-generate-ddl
  • https://www.eolink.com/news/post/14975.html

HikariCP 設定

  • minimumIdle 是 HikariCP 在连接池中维护的最小空闲连接数
  • maximumPoolSize 配置最大池大小
  • idleTimeout 是允许连接在连接池中空闲的最长时间
  • maxLifetime 是池中连接关闭后的最长生命周期(以毫秒为单位)
  • connectionTimeout 是客户端等待连接池连接的最大毫秒数
  • https://www.cnblogs.com/chaojizhengui/p/Hikari_.html

JPA

Bean Type

  • singleton (default)
    • 預設的bean scope,整個IoC容器中只會有一個實例,又稱單例
  • prototype
    • 每次被調用(注入)時都是產生新的實例。
    • 若bean有狀態(stateful),使用 prototype bean。
    • 注意若注入的對象為 singleton bean 的成員,則該 prototype 僅在 singleton 對象初始時實例化一次,也就是說每次 singleton bean 被調用時使用的 prototype bean 都是同一個。
  • request
    • Web 環境才有的 scope。
    • 實例的 scope 為 HTTP Request,同個 request 的實例為同一個,也就是不同 request 的實例是不同的
  • session
    • Web 環境才有的 scope。
    • 實例的 scope 為 HTTP Session,同個 sessio n的實例為同一個,也就是不同 session 的實例是不同的。
  • application
    • Web 環境才有的 scope。
    • 實例的 scope 為 ServletContext,同個 ServletContext 的實例為同一個,也就是不同 ServletContext 的實例是不同的。
  • websocket
    • Web 環境才有的 scope。
    • 實例的 scope 為 WebSocket,同個 WebSocket 的實例為同一個,也就是不同 WebSocket 的實例是不同的。
  • 參考
  • sample code

Lombok

  • @Accessors
    • chain = true:
      • 原本 setter 的方法回傳 void,但標註 @Accessors(chain = true) 後,回傳為該物件本身
        @Data
        @Accessors(chain = true)
        public class EmployEntity {
        
        	private Intger id;
        }
        
        
        原本 setter id 的 method 為
        public void setId(Integer id){
        }
        
        被改寫為
        public EmployEntity setId(Integer id){
        }
        

Unit test

加減密

dependency check

  • 在 pom.xml 新增 plugin 內容如下:
      <plugin>
        <groupId>org.owasp</groupId>
        <artifactId>dependency-check-maven</artifactId>
        <version>8.1.1</version>
        <executions>
            <execution>
                <goals>
                    <goal>check</goal>
                </goals>
            </execution>
        </executions>
      </plugin>
    
  • 執行 mvn org.owasp:dependency-check-maven:check
  • 在 target 會產生 dependency-check-report.html 的檔案
  • summary 會顯示有問題的 dependency
    • 提高 dependency 的版號
    • 確認使用新的 dependency 版本後,可以繼續執行專案

改寫 res

xml

打包時,額外包使用到的 jar 檔

  • jar 與 war 差異:jar只會將程式打包,不會額外包入使用到的 jar 檔
  • 在 pom.xml 裏面新增 plugin
      <plugin>
      	<groupId>org.apache.maven.plugins</groupId>
      	<artifactId>maven-dependency-plugin</artifactId>
      	<executions>
      		<execution>
      			<id>copy-dependencies</id>
      			<phase>package</phase>
      			<goals>
      				<goal>copy-dependencies</goal>
      			</goals>
      			<configuration>
      				<outputDirectory>${project.build.directory}/lib</outputDirectory>
      				<overWriteReleases>false</overWriteReleases>
      				<overWriteSnapshots>false</overWriteSnapshots>
      				<overWriteIfNewer>true</overWriteIfNewer>
      			</configuration>
      		</execution>
      	</executions>
      </plugin>
    
  • 執行 maven package 的時候,會在 target 產生 lib(在 plugin 有描述) folder,擺放全部使用到的 jar

Log 設定

  • 輸出樣式

    • 在 log4j2 的 LOG_PATTERN 進行設定
  • 新增輸出站位符號

發送 API RestTemplate

  • 發送方式

    • 設定 header
    • 設定 request
    • 設定 response
    // 設定 header
    HttpHeaders headers =  new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    
    // 設定 request
    E2eeRequest e2eeRequest = new E2eeRequest();
    
    // 組合為請求
    HttpEntity<E2eeRequest> requestEntity = new HttpEntity<E2eeRequest>(e2eeRequest, headers);
    
    // 發送請求
    RestTemplate restTemplate = new RestTemplate();
    E2eeResponse e2eeResponse = restTemplate.postForObject(e2eUrl, requestEntity,  E2eeResponse.class);
    
  • 設定 timeout

     SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
     factory.setConnectTimeout(1000);
     factory.setReadTimeout(1000);
     
     //...
     restTemplate.setRequestFactory(factory);
     
    
    • 超過 timeout 時間時,就會拋出 exception
    • 預設沒有 timeout 時間上線
  • https://stackoverflow.com/questions/11537591/resttemplate-default-timeout-value

  • https://www.gushiciku.cn/pl/20Ak/zh-tw

(排程) Job

spring-boot's People

Contributors

frank0321 avatar

Stargazers

Shouzhi avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.