Gateway gateway learning summary

Keywords: Spring Redis Nginx Mobile

An overview of microservices:
Micro-service gateway is a system! By exposing the gateway system of the micro-service, it is convenient for us to carry out relevant authentication, security control, log unified processing, and easy to monitor related functions!
What are the technologies to implement the micro service gateway?
1 nginx: nginx is a high performance http and reverse proxy web server, and colleagues also provide IMAP/POP3/SMTP services. It can support 50,000 concurrent links, and the cpu, memory and other resources consumption is very low, running very stable!
2 Zuul: Zuul is a load balancer based on JVM routing and service terminals produced by Netflix. Unfortunately, it has to be replaced by Gateway.
3 Spring-Cloud-Gateway: Spring-based gateway project, integrated circuit breaker, path rewriting, better performance than Zuul! We can use getaway gateway technology to seamlessly link to spring cloud-based micro-service development!
How to use the second micro service gateway?

 1 Fighting Project Adding Dependence
		<dependency>
	          <groupId>org.springframework.cloud</groupId>
	          <artifactId>spring-cloud-starter-gateway</artifactId>
	    </dependency>
        <dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
		</dependency>
 2 Create a boot class: Gateway Application
@SpringBootApplication
@EnableEurekaClient
public class GatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
    }
}
3 Create application.yml under resources
spring:
  cloud:
    gateway:
      globalcors:
        corsConfigurations:
          '[/**]':
            allowedOrigins: "*"
            allowedMethods:
            - GET
            - POST
            - PUT
            - DELETE
      routes:
      - id: goods
        uri: lb://goods
        predicates:
        - Path=/goods/**
        filters:
        - StripPrefix=1
      - id: system
        uri: lb://system
        predicates:
        - Path=/system/**
        filters:
        - StripPrefix=1
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:9002/eureka
  instance:
    prefer-ip-address: true
server:
  port: 9102

Introduction of Three Gateway Filter
Gateway filters, different requirements, different ways of filtering. Each filter, filtering mode operation sequence is different! The main role is to achieve some ip blacklist interception, specific address interception and so on! The main process is to achieve two interfaces GlobalFilter and Ordered, and then by writing yml configuration files, to filter, so as to achieve. To the role of filters!

1 How to use it      Establish IpFilter
	@Component
  public class IpFilter implements GlobalFilter, Ordered {

  @Override
   public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

    System.out.println("Pass through the first filter IpFilter");
    ServerHttpRequest request = exchange.getRequest();
    InetSocketAddress remoteAddress = request.getRemoteAddress();
    System.out.println("ip:"+remoteAddress.getHostName());
    return chain.filter(exchange);
}

@Override
public int getOrder() {
    return 1;
}

}

Gateway Current Limitation - Frequent Access
When our system is frequently requested, it will put pressure on our servers, and it is likely to destroy our server system, so at this time we must limit the flow. There are mainly two kinds of current limitation, one is based on ip, the other is based on users!
There are many kinds of current limiting algorithms. Here, the token bucket algorithm is mainly introduced.

 A request must have a token before it can be processed.
 2. According to the size of replenish Rate, tokens are added to the bucket at a certain rate.
 The number of tokens in three buckets can be set to the maximum. If the number exceeds, a new token will be rejected or discarded.
 4. After the request arrives, the token is obtained first, and the token can be used for other business logic codes. After the business logic is processed, the token is deleted.
 There is also a minimum number of tokens in the bucket. When the token in the bucket reaches the minimum, the token will not be deleted after the request is processed, in order to ensure sufficient current limitation! [The token bucket algorithm illustrates inserting a picture description here] (https://img-blog.csdnimg.cn/20190722172114579.png?X-oss-process=image/watermark, type_ZmZ3ZpoW5naG) VpdGk, shadow_10, text_aHR0cHM6Ly9ibG9nLmNzG4ubmV0L3UwMTM5OTE3NTE=, size_16, color_FFFFFF, t_70)

code implementation
1 spring cloud gateway is implemented by default using Rete Limter current limiting algorithm of redis. So we need to introduce redis dependencies first (here we need to use a responsive redis dependency spring-boot-starter-data-redis-reactive)

  <!--redis-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
//Define KeyResolver in Startup Class
@Bean
public KeyResolver ipKeyResolver() {
    return new KeyResolver() {
        @Override
        public Mono<String> resolve(ServerWebExchange exchange) {
            return Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
        }
    };
}
//configuration file
 spring:
  application:
    name: sysgateway
  cloud:
    gateway:
      globalcors:
        cors-configurations:
          '[/**]': # Match all requests
            allowedOrigins: "*" #Cross-domain processing allows all domains
            allowedMethods: # Supporting methods
            - GET
            - POST
            - PUT
            - DELETE
      routes:
      - id: goods
        uri: lb://goods
        predicates:
        - Path=/goods/**
        filters:
        - StripPrefix= 1
        - name: RequestRateLimiter #Request number limit name cannot be written casually 
          args:
            key-resolver: "#{@ipKeyResolver}"    #Setting rules for restrictions This restriction on ip can also restrict users
            redis-rate-limiter.replenishRate: 1  #The number of requests per second is now 1 
            redis-rate-limiter.burstCapacity: 2  #How many times can an emergency be allowed this time to highlight the 429 status? 
      - id: system
        uri: lb://system
        predicates:
        - Path=/system/**
        filters:
        - StripPrefix= 1
  # Configuring Redis 127.0.0.1 can omit configuration
  redis:
    host: 192.168.200.128
    port: 6379
server:
  port: 9101
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:6868/eureka
  instance:
    prefer-ip-address: true

Encryption algorithm:
Encryption is divided into reversible encryption and irreversible encryption.
Reversible is divided into symmetric and asymmetric
Reversible Advantages: Symmetric encryption algorithm has the advantages of open algorithm, less computation, fast encryption speed and high encryption efficiency.
Disadvantage: No asymmetric encryption security.
Usage: Used to store sensitive but decryptable information such as user's mobile phone number and ID card.
Common symmetric encryption algorithms are:

AES,DES,3DES,Blowfish,IDEA,RC4,RC5,RC6,HS256

Non-pairwise encryption:

Two keys: public key and private key, public key encryption and private key decryption
 Interpretation: Two pairs of keys are generated at the same time: private key and public key. Private key is kept secret and public key can be sent to trusted client.

Encryption and decryption:

  •        Private key cryptography, which requires the possession of a private key or a public key to be decrypted (private key cryptography is equivalent to signature)
    
  •        Public key encryption, private key can be decrypted
    

Signature:

- Private key signature, holding public key to verify whether it has been tampered with.

Advantages: Compared with symmetric encryption, asymmetric encryption has better security; they get married later and have better effect and faster speed.

Disadvantage: The disadvantage of asymmetric encryption is that it takes a long time to encrypt and decrypt, and it is only suitable for encrypting a small amount of data.

Purpose: Usually used for signature and authentication. Private-key servers are saved for encryption, and public-key clients hold them for decryption or verification of tokens or signatures.

Common asymmetric encryption algorithms are RSA, DSA (digital signature), ECC (mobile device), RS256 (RSA signature using SHA-256).

Irreversible Encryption Algorithms

	Interpretation: Once encrypted, the original password cannot be decrypted back.

	Categories: Hash encryption algorithm, hash algorithm, digest algorithm, etc.

	Usage: It is generally used to verify the correctness of downloaded files, and can be seen in downloaded files on the website. It stores user sensitive information, such as password, card number and other non-decryptable information.

Base64 encoding: It's a form of encoding, not an encryption method!
Online coding tools:

http://www.jsons.cn/img2base64/

http://base64.xpcha.com/

BCrypt cryptographic encryption (irreversible)

Posted by tejama on Mon, 22 Jul 2019 03:02:49 -0700