In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article focuses on "how to configure the use of redis", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn how to configure the use of redis!
Spring-data-redis is the redis support part of the spring-data module, referred to as "SDR". It provides a high degree of encapsulation based on the jedis client API and integration with the spring container. In fact, the jedis client is simple and lightweight enough, while spring-data-redis is suspected of being "overdesigned".
The jedis client has the following deficiencies in programming implementation:
1) connection management lacks automation, and the design of connection-pool lacks necessary container support.
2) data operations need to focus on "serialization" / "deserialization", because the data types accepted by the client API of jedis are string and byte, and additional support is needed for structured data (json,xml,pojo) operations.
3) transaction operations are purely hard-coded
4) pub/sub function, lack of necessary design pattern support, too much attention for developers.
1. Redis usage scenarios
Redis is an open source API that is written in ANSI C language, supports the network, can be memory-based and persistent, and provides API in multiple languages.
As we all know, database bottlenecks are the most common in daily applications. Due to the limitation of disk IO performance due to the large amount of data and frequent query, the performance of the project is getting lower and lower.
At this time, the memory-based caching framework can solve many of our problems. Such as Memcache,Redis and so on. Put some frequently used data into the cache to read, greatly reducing the burden of the database. The performance of the system is improved. In fact, the same is true for secondary caching of hibernate and Mybatis. The high-speed read and write speed of memory is used to solve the bottleneck of hard disk.
two。 Configure to use redis
The configuration in applicationContext-dao.xml is as follows:
The database.properties configuration file is as follows:
Redis.maxIdle=10
Redis.maxActive=20
Redis.maxWait=10000
Redis.testOnBorrow=true
Redis.host=192.168.1.76
Redis.port=6379
Redis.pass=password1
Spring-data-redis provides a variety of serializer strategies, which is very convenient for developers using jedis. Sdr provides four built-in serializer:
JdkSerializationRedisSerializer: using JDK serialization means (serializable interface, ObjectInputStrean,ObjectOutputStream), data is stored in byte stream, POJO object is accessed in scenarios, pojo classes are serialized through ObjectInputStream/ObjectOutputStream using JDK serialization mechanism, and byte sequences are eventually stored in redis-server, which is the most commonly used serialization strategy at present.
StringRedisSerializer: a scenario in which the string is encoded and the data is stored in string, and the Key or value is the string. The byte sequence of the data is encoded into string according to the specified charset, which is the direct encapsulation of "new String (bytes, charset)" and "string.getBytes (charset)". Is the most lightweight and efficient strategy.
JacksonJsonRedisSerializer:json format storage, jackson-json tools provide the conversion ability between javabean and json, you can serialize pojo instances to json format and store them in redis, or you can convert json format data into pojo instances. Because the jackson tool needs to specify the Class type explicitly when serializing and deserializing, this policy is slightly more complex to encapsulate. [jackson-mapper-asl tool support required]
OxmSerializer:xml format storage, which provides the ability to convert javabean to xml, the currently available tripartite support including jaxb,apache-xmlbeans;redis stored data will be xml tools. However, using this strategy, programming will be somewhat difficult and least efficient; it is not recommended. [support of spring-oxm module is required]
JdkSerializationRedisSerializer and StringRedisSerializer are the most basic serialization strategies, where "JacksonJsonRedisSerializer" and "OxmSerializer" are based on stirng storage, so they are more "advanced" serialization (ultimately using string to parse and build java objects). JdkSerializationRedisSerializer and StringRedisSerializer are the most basic strategies for "serialization and sending serialization". In principle, we can store data in any format for applications to access and parse (including other tools such as app,hadoop), but it is still not recommended to use "JacksonJsonRedisSerializer" and "OxmSerializer" directly at design time, because whether it is json or xml, they are still String. If your data needs to be parsed by third-party tools, then the data should use StringRedisSerializer instead of JdkSerializationRedisSerializer.
Four kinds of serializer need to be declared in RedisTemplate, and the default is "JdkSerializationRedisSerializer":
1) keySerializer: the serialization strategy adopted by key for ordinary Kmurv operations
2) serialization strategy adopted by valueSerializer:value
3) hashKeySerializer: the serialization strategy of hash-key in hash data structure
4) serialization strategy of hashValueSerializer:hash-value
In any case, StringRedisSerializer is recommended for key/hashKey.
Spring-data-redis provides the following features for jedis:
1. Automatic connection pool management, providing a highly encapsulated "RedisTemplate" class
two。 A large number of api in jedis client are classified and encapsulated, and the same type of operation is encapsulated as operation interface.
ValueOperations: simple Kmurv operation
SetOperations:set type data operation
ZSetOperations:zset type data operation
HashOperations: data manipulation for map types
ListOperations: data manipulation for list types
3. The "bound" (binding) convenient operation API for key is provided. You can encapsulate the specified key through bound, and then perform a series of operations without "explicitly" re-specifying the Key, that is, BoundKeyOperations:
BoundValueOperations
BoundSetOperations
BoundListOperations
BoundSetOperations
BoundHashOperations
3. The use of RedisTemplate
As a template class, this class provides a lot of api that can quickly use redis without having to maintain connections and transactions on your own. Initially, the BaseRedisDao I created inherited from this class. The advantage of inheritance is that I can freely control the serializer in each Dao and control whether I need a transaction or not. I don't need to know about this first, just follow my current configuration method. Template provides a series of operation, such as valueOperation,HashOperation,ListOperation,SetOperation, to manipulate Redis of different data types. In addition, RedisTemplate also provides the corresponding * OperationsEditor, which is used to directly inject the corresponding Operation through RedisTemplate.
Core code:
Package com.npf.dao.impl
Import java.util.ArrayList
Import java.util.List
Import java.util.Map
Import java.util.Map.Entry
Import javax.annotation.Resource
Import org.springframework.beans.factory.annotation.Autowired
Import org.springframework.data.redis.core.HashOperations
Import org.springframework.data.redis.core.RedisTemplate
Import org.springframework.stereotype.Repository
Import com.npf.dao.StudentDao
Import com.npf.model.Student
@ Repository
Public class StudentDaoImpl implements StudentDao {
@ Autowired
Private RedisTemplate redisTemplate
@ Resource (name= "redisTemplate")
Private HashOperations opsForHash
Public static final String STUDENT = "student"
@ Override
Public void save (Student student) {
OpsForHash.put (STUDENT, student.getId (), student)
}
@ Override
Public Student find (String id) {
Student student = opsForHash.get (STUDENT, id)
Return student
}
@ Override
Public void delete (String id) {
OpsForHash.delete (STUDENT, id)
}
@ Override
Public void update (Student student) {
OpsForHash.put (STUDENT, student.getId (), student)
}
@ Override
Public List findAll () {
Map entries = opsForHash.entries (STUDENT)
List stuList = new ArrayList ()
For (Entry entry: entries.entrySet ()) {
StuList.add (entry.getValue ())
}
Return stuList
}
}
The control layer code is as follows:
Package com.npf.controller
Import java.util.List
Import java.util.UUID
Import org.springframework.beans.factory.annotation.Autowired
Import org.springframework.stereotype.Controller
Import org.springframework.ui.Model
Import org.springframework.web.bind.annotation.RequestMapping
Import org.springframework.web.bind.annotation.RequestParam
Import com.npf.model.Student
Import com.npf.service.StudentService
@ Controller
Public class StudentController {
@ Autowired
Private StudentService studentService
@ RequestMapping ("/ student/save")
Public String saveStudent (Student student) {
String id = UUID.randomUUID () .toString ()
System.out.println (id)
Student.setId (id)
StudentService.save (student)
Return "redirect:/student/find/all"
}
@ RequestMapping ("/ student/update")
Public String updateStudent (Student student) {
StudentService.update (student)
Return "redirect:/student/find/all"
}
@ RequestMapping ("/ student/to/save/form")
Public String toSaveStudentForm () {
Return "save"
}
@ RequestMapping ("/ student/delete")
Public String deleteStudent (@ RequestParam ("id") String id) {
StudentService.delete (id)
Return "redirect:/student/find/all"
}
@ RequestMapping ("/ student/to/update/form")
Public String toUpdateStudentForm (@ RequestParam ("id") String id,Model model) {
Student stu = studentService.find (id)
Model.addAttribute ("stu", stu)
Return "update"
}
@ RequestMapping ("/ student/find/all")
Public String findStudents (Model model) {
List stuList = studentService.findAll ()
Model.addAttribute ("stuList", stuList)
Return "list"
}
}
At this point, I believe you have a deeper understanding of "how to configure the use of redis", might as well come to the actual operation of it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
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.
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.