Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is Spring5's Reactive responsive programming?

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the knowledge about "Spring5 Reactive Reactive Programming". In the actual case operation process, many people will encounter such difficulties. Next, let Xiaobian lead you to learn how to deal with these situations! I hope you can read carefully and learn something!

1 What is responsive programming?

In a word: Reactive programming is a programming paradigm that is universal and focused on data flow and change, and asynchronous.

Wikipedia:

In computing, reactive programming is an asynchronous programming paradigm concerned with data streams and the propagation of change. This means that it becomes possible to express static (e.g. arrays) or dynamic (e.g. event emitters) data streams with ease via the employed programming language(s), and that an inferred dependency within the associated execution model exists, which facilitates the automatic propagation of the change involved with data flow.

Translation:

In computing, reactive programming is an asynchronous programming paradigm that focuses on data flow and change transfer. This means that static (e.g. arrays) or dynamic (e.g. event emitters) data flows can be easily represented using programming languages, and that there are deductible dependencies in the associated execution model that facilitate automatic propagation of changes related to the data flow.

Examples:

For example, in an imperative programming environment, a:=b+c means assigning the result of an expression to a, and then changing the value of b or c has no effect. But in reactive programming, the value of a updates as b or c is updated. A spreadsheet program is an example of responsive programming. Cells can contain literal values or formulas like "=B1+C1," and the value of the cell containing the formula changes depending on the values of other cells.

Responsive programming was originally proposed to simplify the creation of interactive user interfaces and the drawing of real-time system animations, but it is essentially a general programming paradigm.

2 Review Reactor 2.1 What is a Reactor

Or Wikipedia:

The reactor design pattern is an event handling pattern for handling service requests delivered concurrently to a service handler by one or more inputs. The service handler then demultiplexes the incoming requests and dispatches them synchronously to the associated request handlers.

Translation:

The reactor design pattern is an event-handling pattern for handling service requests delivered concurrently to a service handler by one or more inputs. The service handler then demultiplexes incoming requests and dispatches them synchronously to the relevant request handlers.

2.2 Why Reactor?

Reactor is derived from the pattern of synchronous non-blocking I/O multiplexing mechanisms in network IO.

The difference between blocking and non-blocking lies in the first stage, i.e., the data preparation stage. Whether it is blocking or non-blocking, the application actively seeks the kernel for data, and the process of reading the data is 'blocked' until the data is read.

The difference between synchronous and asynchronous is that in the second stage, if the requester takes the initiative to obtain the data, it is a synchronous operation. It should be noted that the read/write operation is also 'blocked' until the data is read out.

If all reads of data are done by the kernel (application processes can still perform other tasks while the kernel reads data), this is asynchronous operation.

In other words,

BIO users are most concerned about "I want to read,"

NIO users are most concerned about "I can read it,"

In the AIO model, users need to pay more attention to "finished reading."

An important feature of NIO is that socket's main read, write, register, and receive functions are non-blocking during the wait-ready phase, and true I/O operations are synchronous blocking (consuming CPU but very high performance).

NIO is a synchronous non-blocking I/O model and the basis for I/O multiplexing.

Basic structure of Reactor mode:

Handle: essentially represents a resource (such as a file descriptor, or socket descriptor for network programming) provided by the operating system; the resource is used to represent an event, which can come from both external and internal sources.

Synchronous Event Demultiplexer: This is itself a system call that waits for an event to occur (there may be one or more events). The caller is blocked when it is invoked until an event is generated on the synchronous event separator. For Linux, synchronous event splitters refer to common I/O multiplexing mechanisms, such as select, poll, epoll, etc. In Java NIO, the component corresponding to the synchronous event separator is the Selector; the corresponding blocking method is the select method.

Event Handler: itself consists of multiple callback methods that constitute application-specific feedback mechanisms for an event. There is no event handler mechanism in Java NIO for us to call or make callbacks, it is written by us. Netty is an upgrade to Java NIO in the role of event handler, which provides us developers with a large number of callback methods for us to implement corresponding callback methods for business logic processing when specific events occur, i.e. ChannelHandler. The methods in ChannelHandler correspond to callbacks for individual events.

Concrete Event Handler: An implementation of an event handler. It itself implements the various callback methods provided by the event handler, thereby implementing business-specific logic. It's essentially a processor implementation that we write.

Initiation Dispatcher: This is essentially the Reactor role. It defines specifications that control how events are scheduled and provides facilities for applications to register and delete event handlers. It itself is the core of the event handler, and the Initiation Dispatcher waits for events to occur via the Synchronous Event Demultiplexer. Once an event occurs, the Initiation Dispatcher first isolates each event, then invokes the event handler, and finally invokes the associated callback method to handle the event. Each callback method in ChannelHandler in Netty is called by an EventLoop in bossGroup or workGroup.

2.3 Classic implementation of Reactor pattern-Netty

Netty's thread pattern is a classic pattern that implements the Reactor pattern.

Structure corresponds to:

NioEventLoop ---- Initiation Dispatcher

Synchronous EventDemultiplexer ---- Selector

Evnet Handler ---- ChannelHandler

ConcreteEventHandler ---Implementation of a concrete ChannelHandler

Mode corresponds to:

Netty server uses "multi-reactor thread mode"

mainReactor --- bossGroup(NioEventLoopGroup)

subReactor ---a NioEventLoop in workerGroup(NioEventLoopGroup)

acceptor ---- ServerBootstrapAcceptor

ThreadPool ---User-defined thread pool

Process:

① When the server program is started, ChannelPipeline will be configured. ChannelPipeline is a ChannelHandler chain. All events will trigger a method in Channelhandler when they occur. This event will propagate in ChannelHandler chain in ChannelPipeline. Then, a NioEventLoop is obtained from the bossGroup event loop pool to perform the operation of binding the local port of the server program, the corresponding ServerSocketChannel is registered on the Selector in the NioEventLoop, and the ACCEPT event is registered as the event in which the ServerSocketChannel is interested.

② NioEventLoop event loop starts, at this time, it starts to listen for the connection request of the client.

③ When a client initiates a connection request to the server, NioEventLoop event loop listens to the ACCEPT event, Netty bottom layer will receive this connection, get the connection (SocketChannel) with this client through accept() method, and then trigger ChannelRead event (that is, channelRead method in ChannelHandler will get callback), this event will be executed and propagated in ChannelHandler chain in ChannelPipeline.

4. The readChannel method of ServerBootstrapAcceptor registers the SocketChannel(client connection) to a Selector of NioEventLoop in workerGroup(NioEventLoopGroup), and registers the READ event as the event of interest to SocketChannel. Start the NioEventLoop event loop where SocketChannel is located, and then you can start communication between the client and server.

3 Spring5 Multiple Reactive Support

3.1 Spring Webflux3.1.1 dependencies org.springframework.boot spring-boot-starter-webflux3.1.2 Controller code @RestControllerpublic class HelloController { @GetMapping("/hello") public Mono hello() { return Mono.just("Hello Spring Webflux"); } }3.1.3 Test C:\Users\xxxx\Desktop\sb-reactive>curl http://localhost:8080/helloHello Spring Webflux3.1.4 Differences in Spring MVC and Spring WebFlux patterns

3.2 Spring Data Reactive Respositories 3.2.1 Dependency org.springframework.boot spring-boot-starter-data-redis-reactive3.2.2 Configure public class RedisReactiveConfig { @Bean public ReactiveRedisConnectionFactory connectionFactory() { return new LettuceConnectionFactory("127.0.0.1", 6379); } @Bean public ReactiveStringRedisTemplate reactiveStringRedisTemplate(ReactiveRedisConnectionFactory factory) { return new ReactiveStringRedisTemplate(factory); }}3.3.3 Tests @SpringBootTestclass SbReactiveApplicationTests { @Autowired private ReactiveStringRedisTemplate reactiveRedisTemplate; @Test void contextLoads() { reactiveRedisTemplate .opsForValue().set("1", "zs") .subscribe(b -> System.out.println("success"), e -> System.out.println("error")); How do I understand reactive programming?

There are many concepts, but what is the better value of it than our general request processing?

Explanation:

Reactive Programming, as an extension of Observer mode, is different from traditional imperative programming, such as iterator mode, which pulls data synchronously. Instead, it adopts a scheme in which data publishers push data streams synchronously or asynchronously. When subscribers to the Data Steams hear propagation changes, they react immediately. At the implementation level, Reactive Programming can be combined with functional programming to simplify the bloated nature of object-oriented language syntax, mask the complex details of concurrent implementation, provide orderly operation of data flow, thus improving code readability and reducing Bugs. At the same time, Reactive Programming combines backpressure techniques to solve the problem that the publisher generates data at a higher rate than the subscriber consumes.

"Spring5 reactive programming is what" content introduced here, thank you for reading. If you want to know more about industry-related knowledge, you can pay attention to the website. Xiaobian will output more high-quality practical articles for everyone!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report