In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly shows you "how to use Redis in JavaEE", the content is easy to understand, clear, hope to help you solve doubts, the following let the editor lead you to study and learn "how to use Redis in JavaEE" this article.
Redis is a nosql database of key-value. First stored in memory, will be persisted to disk according to a certain policy, even if the power outage will not lose data. There are many data types supported.
Mainly used for caching database data and web cluster as a central cache to store seesion.
Daemons: in linux or unix operating systems, many services are opened when the system boots. These services are called daemons. To increase flexibility, root can choose the modes that are turned on by the system, which are called runlevels, each of which configures the system in a certain way. A daemon is a process that is detached from the terminal and runs in the background. The daemon is separated from the terminal in order to prevent the information of the process from being displayed on any terminal and the process will not be interrupted by the terminal information generated by any terminal.
CAP theorem
High performance, high availability and scalability
1) nosql database classification
The difference between Redis and Memcache:
Both Redis and Memcache store data in memory, and both are in-memory databases. However, memcache can also be used to cache other things, such as pictures, videos, and so on.
Redis not only supports simple KBE data, but also provides storage of data structures such as list,set,hash.
Virtual memory-Redis swaps some value that has not been used for a long time to disk when the physical memory is used up
Nosql database classification:
2) Redis usage scenarios
Cache:
Put the data that often needs to be queried and rarely modified into the space (memory) where the reading speed is very fast, so that the next access can reduce the time. Reduce the pressure and reduce the visiting time.
Counter:
Counters in Redis are atomic memory operations.
It can solve the problem of inventory overflow. Inventory overflow of purchase, sale and storage system.
Session cache server:
Act as a session cache server when web is clustered
Cache queues, etc.
3) how to save Redis objects
Json string:
You need to convert the object to a json string and treat it as a string. Use set get directly to set or or.
Advantages: easy to set up and get
Cons: no special method is provided, and you need to convert the object to json. (jsonlib)
Bytes: need to make a sequence number, that is, to serialize the object into bytes to save.
If you are worried that the conversion of JSON to objects will consume resources, there are several areas to consider:
The first point is whether there is a performance problem with the JSON transformation lib used.
The second point is the data volume level. If you are storing millions of big data objects, it is recommended to use the storage serialization object method. If there are a small number of data-level objects, or if there are not many data object fields, it is recommended to convert JSON to String.
After all, redis optimizes the storage of character types very well. The specific ways and methods to be adopted also depend on the scenarios you use.
4) Redis data elimination mechanism
In Redis, it is useful to allow users to set the maximum memory usage server.maxmemory, which is useful when memory is limited. For example, four Redis service points are deployed on an 8G machine, each of which allocates 1.5GB of memory to reduce memory strain and obtain more robust services.
The memory size is limited, so do you need to save valid data?
When the Redis in-memory dataset size rises to a certain size, the data elimination strategy is implemented.
Redis provides 6 data elimination strategies:
Volatile-lru: select the least recently used data elimination from the dataset with an expiration time set (server. DB [I]. Obsolete).
Volatile-ttl: select the expired data from the dataset (server. DB [I]. Expires) that will expire.
Volatile-random: arbitrarily select data elimination from a dataset with an expiration time set (server. DB [I]. Expires).
Allkeys-lru: select the least recently used data elimination from the dataset (server. DB [I]. Dict).
Allkeys-random: data elimination from any selection of the dataset (server. DB [I]. Dict)
No-enviction (expulsion): prohibition of eviction data
5) Java operation Redis mode
Using the jedis java client to access the redis server is a bit like accessing mysql through jdbc.
Of course, if spring is integrated, you can use spring data to access redis,spring data, which is just a secondary encapsulation of jedis. JdbcTemplate jdbc relationship is the same.
6) data types stored by Redis
1.String
To save a String to redis, use set (key,value) and get the value with get (key).
2.Hash (commonly used to save objects)
To save a Hash to redis, iterate through the Map, call hset (key,hashKey,hashValue) one by one, and get all the values that have hgetAll (key).
3.List
To save a List to redis, iterate through the List, call lpush (key,value) one by one, and get the value with lrange (key,start,end), start for the start position, end for the end position, and-1 for the end.
Here lpush means to save from the left, that is, to catch up from behind.
4.Set
To save a Set to redis, iterate through the Set, call sadd (key,value) one by one, and get the value with smembers (key).
5.SortedSet
SortedSet means that each of his elements is ordered, the order is determined by its score, and if the socre is the same, it is sorted by value. The way to save to redis is to call zadd (key,score,value) for each element to be saved, and get the value with zrange (key,satrt,end), start for the start position, end for the end position, and-1 for the end.
7) Master-slave replication of Redis
Similar to mysql's master-slave mode, redis's master-slave can improve the availability of the system. After the master node is written to the cache, it will be automatically synchronized to the slave. Master is mainly written, while Slave is mainly read.
It can be realized: read-write separation and disaster recovery.
Disadvantages: delay, because all write operations are operated on Master, and then synchronously updated to Slave, there is a certain delay from Master synchronization to Slave machines. When the system is very busy, the delay problem will be more serious, and the increase in the number of Slave machines will also make this problem more serious.
Configuration process:
Master Redis:192.168.10.1 6379 slave Redis:192.168.10.2 6380
Change the aemonize no in the master-slave redis configuration file redis.conf to yes
Modify from port 6379 in redis configuration file redis.conf to 6380, add slaveof 192.168.10.1 6379
Start the master-slave service
Master Redis:
[root@localhost redis-2.8.3] # src/redis-server / soft/redis-2.8.3-master/redis-2.8.3/redis.conf
From Redis:
[root@localhost redis-2.8.3] # src/redis-server / soft/redis-2.8.3-slave/redis-2.8.3/redis.conf
Test data synchronization
Master Redis:
[root@localhost redis-2.8.3] # src/redis-cli-p 6379 127.0.0.1 set name abc OK 6379 > get name "abc" 127.0.0.1
From Redis:
[root@localhost redis-2.8.3] # src/redis-cli-p 6380 127.0.0.1 get name "abc" 127.0.0.1
The default is read-write separation.
From Redis:
[root@localhost redis-2.8.3] # src/redis-cli-p 6380 127.0.1 set name 6380 > set name 123 (error) READONLY You can't write against a read only slave. Master-slave switch 1, stop master Redis [root@localhost redis-2.8.3] # src/redis-cli-n 6379 shutdown [root@localhost redis-2.8.3] # src/redis-cli-p 6379 Could not connect to Redis at 127.0.0.1 shutdown 6379: Connection refused not connected > 2, set slave Redis to master Redis [root@localhost redis-2.8.3] # src/redis-cli-p 6380 slaveof NO ONE OK3, Test whether to switch from slave Redis to slave redis [root@localhost redis-2.8.3] # src/redis-cli-p 6380 127.0.0.1 set name 6380 > set name 127.0.1 root@localhost redis-2.8.3 > get name "123" 127.0.1 root@localhost redis-2.8.3 6380 > 4. The original master Redis is back to normal. We need to switch back.
1) Save the data of the current master redis
[root@localhost redis-2.8.3] # src/redis-cli-p 6380 127.0.0.1 src/redis-cli 6380 > get name "abc" 127.0.0.1 get name 6380 > set name 127.0.0.1 get name 6380 > get name "123" 127.0.0.1 get name 6380 > save OK 127.0.0.1 get name 6380 > get name "127.0.0.1 purl 6380 >
2) overwrite the copy of the dump.rdb file under the current main redis root directory to the root directory of the original main redis
3) start the original master redis
[root@localhost redis-2.8.3] # src/redis-server / soft/redis-2.8.3-master/redis-2.8.3/redis.conf
4) switch in the current main redis
[root@localhost redis-2.8.3] # src/redis-cli-p 6380 slaveof 192.168.10.1 6379 OK
Common design solutions:
One master and two servants: one Master, two Slave,Slave can only be read but not written. When the Slave is disconnected from the Master, you need to reconnect the slave of to establish the previous master-slave relationship. After the Master dies, the Master relationship still exists and the Master can be restarted.
Pass on: the Master,Slave of the last Slave can be the next Slave can also receive connection and synchronization requests from other slaves, so the slave is used as the Master of the next slave in the chain, which can effectively reduce the writing pressure of Master. If the slave changes midway, the previous data will be erased and the latest one will be re-established.
Counter-customer: when the Master is dead, Slave can type the command slaveof no one to make the current Redis stop synchronizing with other Master redis data and convert it to Master redis.
The principle of replication:
When Slave starts successfully connecting to master, it sends a sync command.
After receiving the command, Master starts the save process and collects all the commands received to modify the dataset. After the background process finishes execution, master will transfer the entire data file to slave to complete a complete synchronization.
Full copy: after the database file data is saved and loaded into memory by the slave service
Incremental copy: Master continues to send all new collected modification commands to slave in turn to complete synchronization
However, as long as you reconnect to the master, a full synchronization (full copy) will be performed automatically.
Sentinel mode:
The automatic version, which is mainly anti-customer, can monitor the failure of the Master library in the background, and automatically convert the slave library into the main library according to the number of votes if it fails. A group of sentinel can monitor multiple Master at the same time.
Steps to use:
1. Create a new sentinel.conf file in the same directory as the redis.conf corresponding to Master. The name must not be wrong.
2. Configure Sentinel and enter the content in the sentinel.conf file:
Sentinel monitor monitored database name (name yourself) ip port 1
Description: the last number 1 above means that after the host is hung up, slave votes to see who will take over as the host, and become the host after the number of votes.
3. Start Sentinel mode:
Command type: redis-sentinel / myredis/sentinel.conf
Note: the above sentinel.conf paths are configured according to their actual conditions.
8) Redis serializer
Ordinary connection users have no way to store Java objects directly into Redis, but we need to provide our own solution-object serialization, then store it in redis, retrieve the serialized content, and convert it to java objects. The wrapper scheme is provided in the Spring template, and the RedisSerializer interface (org.springframework.data.redis.serializer.RedisSerializer) and some implementation classes are provided within it. You can also customize the serializer to implement the RedisSerializer interface. The commonly used ones are: StringRedisSerializer,JdkSerializationRedisSerializer,GenericToStringSerializer.
The default serialization class for RedisTemplate is JdkSerializationRedisSerializer, and if serialized with JdkSerializationRedisSerializer, the serialized object must implement the Serializable interface. In the storage of content, in addition to the content of the attribute, there are other contents, the total length is long, and is not easy to read. We require that the stored data can be easily viewed, desserialized and read.
Both Jackson2JsonRedisSerializer and GenericJackson2JsonRedisSerializer can be serialized into json, but the latter adds the @ class attribute to the json, the full-path package name of the class, to facilitate deserialization. If List is stored in the former, an error will be reported if TypeReference is not specified during deserialization: java.util.LinkedHashMap cannot be cast to.
9) websocket
WebSocket is a protocol that HTML5 began to provide for full-duplex communication over a single TCP connection.
WebSocket makes it easier to exchange data between the client and the server, allowing the server to actively push data to the client. In WebSocket API, only one handshake is needed between the browser and the server, and a persistent connection can be directly created between the browser and the server for two-way data transmission.
In WebSocket API, the browser and the server only need to shake hands, and then a fast channel is formed between the browser and the server. Data can be transmitted directly between the two.
Now, in order to implement the push technology, many websites use Ajax polling. Polling is a browser in which the browser issues a HTTP request to the server at a specific time interval (such as every 1 second), and then the server returns the latest data to the client. This traditional mode brings obvious disadvantages, that is, browsers need to constantly send requests to the server, but HTTP requests may contain long headers, in which the really effective data may be only a small part, which will obviously waste a lot of bandwidth and other resources.
WebSocket protocol is essentially a TCP-based protocol.
In order to establish a WebSocket connection, the client browser first initiates a HTTP request to the server, which, unlike the usual HTTP request, contains some additional header information, in which the additional header information "Upgrade: WebSocket" indicates that this is a HTTP request to apply for protocol upgrade. The server parses the additional header information and then generates the reply information and returns it to the client. The WebSocket connection between the client side and the server side is established, and both parties can freely transmit information through this connection channel, and the connection will persist until the client or server side actively closes the connection.
Websocket event trigger mechanism:
Open:
Once the server responds to the WebSocket connection request, the open event triggers and a connection is established. The callback function corresponding to the open event is called onopen.
By the time the open event is triggered, the protocol handshake is complete and the WebSocket is ready to send and receive data. If the application receives an open event, it can be determined that the WebSocket server successfully processed the connection request and agreed to communicate with the application.
Message:
The WebSocket message contains data from the server. You may also have heard of the WebSocket frames (Frame) that make up WebSocket messages. Chapter 3 discusses the concepts of messages and frames in detail. To understand the way messages use API, WebSocket API only outputs the complete message, not the WebSocket frame. The message event is triggered when a message is received, and the callback function corresponding to that event is onmessage.
In addition to text, WebSocket messages can also handle binary data, which is handled as Blob messages or ArrayBuffer messages. Because applications that set the WebSocket message binary data type affect binary messages, you must decide which type to use for the client-side binary input data before reading the data.
Error:
The error event is triggered in response to an unexpected failure. The callback function corresponding to this event is onerror. Errors can also cause the WebSocket connection to close. If you receive an error event, you can expect that the close event will be triggered soon. The code and reason in the close event can sometimes tell you the root cause of the error. Error event handlers are the best place to invoke server reconnect logic and handle exceptions from WebSocket objects.
Close:
The close event is triggered when the WebSocket connection is closed. The callback function corresponding to the close event is onclose. Once the connection is closed, the client and server can no longer receive or send messages.
Note: the WebSocket specification also defines ping and pong frames, which can be used for persistent connection (keep-alive), heartbeat, network state detection, delay measurement, etc., but WebSocket API currently does not output these features. Although the browser accepts ping frames, it does not trigger the ping event on the corresponding WebSocket. Instead, the browser automatically responds to the pong frame. However, if the browser instantiated ping does not receive a pong reply for a period of time, it may trigger the close event of the connection.
The onclose event handler is also triggered when the close () method is called to terminate the connection to the server; the WebSocket close event is triggered when the connection is closed for a variety of reasons, such as a failed connection or a successful WebSocket closing handshake. The WebSocket object property readyState reflects the state of the connection (2 is closing, 3 is closed).
The close event has three useful properties (property) that can be used for error handling and recovery: wasClean, code, and error. The wasClean property is a Boolean property that indicates whether the connection closes smoothly. This property is true if the shutdown of WebSocket is a response to a close frame from the server. This property is false if the connection is closed for some other reason (for example, because the underlying TCP connection is closed). The code and reason attributes indicate the off handshake status sent by the server. These properties are consistent with the code and reason parameters in the WebSocket.close () method.
Colored eggs at the end of the article
With regard to the knowledge points mentioned above, I have summed up most of the architecture interview questions and answers involved in the interview by programmers with 1 to 5 years of development experience. I have made documents and architecture video materials to share with you for free (including Dubbo, Redis, Netty, zookeeper, Spring cloud, distributed, high concurrency and other architecture technical materials). I hope it can help you review before the interview and find a good job. It also saves time for everyone to search for information on the Internet to learn, and you can also follow me for more practical information to share in the future.
Data acquisition method QQ group search "708701457" can be obtained free of charge.
The above is all the contents of the article "how to use Redis in JavaEE". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
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: 273
*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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.