Skip to main content

HTTP 1.1 and HTTP 2 On Java On Ease


REST API In HTTP/2



HTTP/1.1 is good, but as our applications is growing in complexity , in size in scale etc. This is a great time to make the change to HTTP/2.

HTTP/2 has a binary framing layer. Its backward compatibility with HTTP/1.x clients and servers. 


New binary framing : 

HTTP/1.x : Uses newline delimited text to transfer the data. It is more prone  to error compared to binary.

HTTP/2 : It uses binary format. In the transfer layer.






The design is to how the data is encoded between sockets and the HTTP APIs of our application.
The web container will take care of encoding based on HTTp Version.

traditional GET, PUT, POST, DELETE

HTTP/2 breaks down the HTTP protocol communication into an exchange of binary-encoded frames, which are then mapped to messages that belong to a particular stream, all of which are multiplexed within a single TCP connection.

1.Binary Processing: Binary content is faster, lighter, and more compact. Instead of having four different message parsing options in HTTP/1.x, HTTP/2 has one. The binary content supports processing of capitalizations, whitespaces, blank lines and few other notions difficult to portray in text.

2. Multiplexing: HTTP/1.x was fundamentally created over the principle that only 1 response can be delivered at a time. This resulted into response queueing and blocking, slowing down the TCP connection. This meant until now, the client had to guess the correct order of responses it needs to fetch to be able to process things quickly.





HTTP/2 The new binary streams make possible of request and response multiplexing. Hence the client just need one connection to deliver multiple requests and responses in parallel, without any of them blocking each other. Hence it delivers lower page load times by eliminating unnecessary latency and improving the utilisation of available network capacity.

3. Header Compression:  HTTP/2 uses the HPACK compression technique to compress header data across requests and responses.



HPACK compresses the headers using Huffman encoding, while the client and server maintain a list of previously seen headers for quicker encoding and interpretation.
In today’s average requests, we can see headers crossing several kilobytes with cookies, and header compression greatly improves efficiency.

4. Server Push: In HTTP/1.x, a server can communicate to the client only when a request is made to it, and it can communicate only by responding to that particular request. In HTTP/2 however, a server can send multiple responses to a single request. Thus, in addition to responding, the server can push other useful information to the client.
For example, while loading a webpage, the server can start sending the javascript files and stylesheets right away, without waiting for the client to ask for them. It may also be used to activity update the client’s cache for faster rendering.

How to move to HTTP/2?

No real changes need to be made to the application layer to transition to HTTP/2, as the changes are in the encoding and information transfer mechanisms.

If you are using cURL , just check the current version with

curl --version

You will be responded with a list of protocols : dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtsp smb smbs smtp smtps telnet tftp . If you do not see http2 included there, you can simply update your cURL version.

Mac users can simply do

brew reinstall curl --with-openssl --with-nghttp2

Tomcat version 8.5.x . All we need to do is add the HTTP 2 upgrade protocol to Tomcat’s connector. We can do that by customizing the embedded Tomcat container:

@Bean
public EmbeddedServletContainerCustomizer tomcatCustomizer() {
return (container) -> {
if (container instanceof TomcatEmbeddedServletContainerFactory) {
((TomcatEmbeddedServletContainerFactory) container)
.addConnectorCustomizers((connector) -> {
connector.addUpgradeProtocol(new Http2Protocol());
});
}
};
}


You need to add the HTTP 2 upgrade protocol to Tomcat's connector. You can do that by customizing the embedded Tomcat container:

Java 8:

@Bean
public EmbeddedServletContainerCustomizer tomcatCustomizer() {
    return (container) -> {
        if (container instanceof TomcatEmbeddedServletContainerFactory) {
            ((TomcatEmbeddedServletContainerFactory) container)
                    .addConnectorCustomizers((connector) -> {
                connector.addUpgradeProtocol(new Http2Protocol());
            });
        }
    };
}

Java 7:

@Bean
public EmbeddedServletContainerCustomizer tomcatCustomizer() {
    return new EmbeddedServletContainerCustomizer() {

        @Override
        public void customize(ConfigurableEmbeddedServletContainer container) {
            if (container instanceof TomcatEmbeddedServletContainerFactory) {
                ((TomcatEmbeddedServletContainerFactory) container)
                        .addConnectorCustomizers(new TomcatConnectorCustomizer() {
                    @Override
                    public void customize(Connector connector) {
                        connector.addUpgradeProtocol(new Http2Protocol());
                    }

                });
            }
        }

    };
}

Comments

Popular posts from this blog

How to create Annotation in Spring boot

 To create Custom Annotation in JAVA, @interface keyword is used. The annotation contains :  1. Retention :  @Retention ( RetentionPolicy . RUNTIME ) It specifies that annotation should be available at runtime. 2. Target :  @Target ({ ElementType . METHOD }) It specifies that the annotation can only be applied to method. The target cane be modified to:   @Target ({ ElementType . TYPE }) for class level annotation @Target ({ ElementType . FIELD }) for field level annotation @Retention ( RetentionPolicy . RUNTIME ) @Target ({ ElementType . FIELD }) public @ interface CustomAnnotation { String value () default "default value" ; } value attribute is defined with @ CustomAnnotation annotation. If you want to use the attribute in annotation. A single attribute value. Example : public class Books {           @CustomAnnotation(value = "myBook")     public void updateBookDetail() {         ...

Kafka And Zookeeper SetUp

 Kafka And Zookeeper SetUp zookeeper download Link : https://www.apache.org/dyn/closer.lua/zookeeper/zookeeper-3.8.3/apache-zookeeper-3.8.3-bin.tar.gz Configuration: zoo.conf # The number of milliseconds of each tick tickTime =2000 # The number of ticks that the initial # synchronization phase can take initLimit =10 # The number of ticks that can pass between # sending a request and getting an acknowledgement syncLimit =5 # the directory where the snapshot is stored. # do not use /tmp for storage, /tmp here is just # example sakes. dataDir =/tmp/zookeeper # the port at which the clients will connect clientPort =2181 4 char whitelist in command arguments 4lw.commands.whitelist =* Start ZooKeeper Server $ bin/zkServer.sh start Check zookeeper status dheeraj.kumar@Dheeraj-Kumar bin % echo stat | nc localhost 2181 stat is 4 character whitelisted argument  Check Kafka running status : echo dump | nc localhost 2181 | grep broker Responsibility of Leader in Zookeeper: 1. Distrib...

Cache Policy

Cache policies determine how data is stored and retrieved from a cache, which is a small and fast storage area that holds frequently accessed data to reduce the latency of accessing that data from a slower, larger, and more distant storage location, such as main memory or disk. Different cache policies are designed to optimize various aspects of cache performance, including hit rate, latency, and consistency. Here are some common types of cache policies: Least Recently Used (LRU): LRU is a commonly used cache replacement policy. It evicts the least recently accessed item when the cache is full. LRU keeps track of the order in which items were accessed and removes the item that has not been accessed for the longest time. First-In-First-Out (FIFO): FIFO is a simple cache replacement policy. It removes the oldest item from the cache when new data needs to be stored, regardless of how frequently the items have been accessed. Most Recently Used (MRU): MRU removes the most recently accessed ...