search
HomeDatabaseRedisHow to configure and use redis
How to configure and use redisMay 31, 2023 pm 11:31 PM
redis

Spring-data-redis is the support part for redis in 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 enough Simple and lightweight, spring-data-redis is suspected of being "over-designed".
The jedis client has the following shortcomings in programming implementation:
1) Connection management lacks automation, and the design of connection-pool lacks necessary container support.
2) Data operations need to pay attention to "serialization"/"deserialization", because the data types accepted by jedis's client API are string and byte, and additional operations are required for structured data (json, xml, pojo) support.
3) Transaction operations are purely hard-coded
4) The pub/sub function lacks necessary design pattern support, which requires too much attention for developers.
1. Redis usage scenarios
Redis is an open source log-type Key-Value database written in ANSI C language, supports network, can be memory-based and persistent, and provides APIs in multiple languages.
We all know that in daily applications, database bottlenecks are the most likely to occur. Due to the large amount of data and frequent queries, the performance of the project is getting lower and lower due to the limitations of disk IO performance.
At this time, the memory-based caching framework can solve many of our problems. For example Memcache, Redis, etc. Putting some frequently used data into the cache for reading greatly reduces the burden on the database. Improved system performance. In fact, the same is true for the second-level cache of hibernate and Mybatis. Use the high-speed reading and writing speed of memory to solve the bottleneck of the hard disk.

2. Configure and use redis

Configure as follows in applicationContext-dao.xml:

  1. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  2. xmlns:context="http://www.springframework.org/schema/context"

  3. xmlns:mongo="http://www.springframework.org/schema/data/mongo"

  4. xmlns:aop="http://www.springframework.org/schema/aop"

  5. xsi:schemaLocation="http://www.springframework.org/schema/beans

  6.                                                                                                                                                                                                                                                                                                                                                                                                                                                              http://www.springframework.org/schema/context/spring-context-3.0.xsd

  7. http://www.springframework.org/schema/aop

  8. http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

  9. #

  10.          

  11. ##                                                                                                                       ,,,,,,,,,,,                                                                                                                    ,,,,,,,,,,,               
  12.               

  13.           

  14.           

  15.       

  16.            

  17.            

  18.            

  19.            

  20.       

  21.            

  22.           

  23.           

  24.           

  25.       

  26.       

  27.               

  28.               

  29.               

  30.               

  31.               

  32.       

  33.   

  34.   

database.properties配置文件如下:

  1. redis.maxIdle=10  

  2. redis.maxActive=20  

  3. redis.maxWait=10000  

  4. redis.testOnBorrow=true  

  5. redis.host=192.168.1.76  

  6. redis.port=6379  

  7. redis.pass=password1  

spring-data-redis提供了多种serializer策略,这对使用jedis的开发者而言,实在是非常便捷。sdr提供了4种内置的serializer:

  • JdkSerializationRedisSerializer:使用JDK的序列化手段(serializable接口,ObjectInputStrean,ObjectOutputStream),数据以字节流存储,POJO对象的存取场景,使用JDK本身序列化机制,将pojo类通过ObjectInputStream/ObjectOutputStream进行序列化操作,最终redis-server中将存储字节序列,是目前最常用的序列化策略。

  • StringRedisSerializer:字符串编码,数据以string存储,Key或者value为字符串的场景,根据指定的charset对数据的字节序列编码成string,是“new String(bytes, charset)”和“string.getBytes(charset)”的直接封装。是最轻量级和高效的策略。

  • JacksonJsonRedisSerializer: json format storage, the jackson-json tool provides conversion capabilities between javabean and json. It can serialize pojo instances into json format and store them in redis, or convert json format data into pojo instances. Because the Jackson tool needs to explicitly specify the Class type when serializing and deserializing, this strategy is slightly more complicated to encapsulate. [Requires jackson-mapper-asl tool support]

  • OxmSerializer: xml format storage, providing the ability to convert javabeans to xml. Currently available three-party support includes jaxb, apache-xmlbeans; the data stored in redis will be xml tools. However, using this strategy will make programming more difficult and the most efficient; it is not recommended. [Requires spring-oxm module support]

Among them, JdkSerializationRedisSerializer and StringRedisSerializer are the most basic serialization strategies. Among them, "JacksonJsonRedisSerializer" and "OxmSerializer" are based on string storage, so they are more "advanced" serialization (eventually using string parsing and constructing java objects). JdkSerializationRedisSerializer and StringRedisSerializer are the most basic strategies for "serialization and serialization". In principle, we can store data in any format for application access and parsing (applications include app, hadoop and other tools), but It is still not recommended to use "JacksonJsonRedisSerializer" and "OxmSerializer" directly at design time, because whether it is json or xml, they themselves are still String. If your data needs to be parsed by third-party tools, the data should use StringRedisSerializer instead of JdkSerializationRedisSerializer.

​ 4 types of serializers need to be declared in RedisTemplate, the default is "JdkSerializationRedisSerializer":

1) keySerializer: For ordinary K-V operations, the serialization strategy adopted by key
2) valueSerializer: The serialization strategy adopted by value
3) hashKeySerializer: In the hash data structure, the serialization strategy of hash-key
4) hashValueSerializer: hash-value serialization strategy

In any case, it is recommended that key/hashKey use StringRedisSerializer.

spring-data-redis provides the following functions for jedis:

1. Connection pool automatic Management, providing a highly encapsulated "RedisTemplate" class

2. Classified and encapsulated a large number of APIs in the jedis client, and encapsulated the same type of operations into operation interfaces

  • ValueOperations: Simple K-V operation

  • SetOperations: set type data operations

  • ZSetOperations: zset type data operations

  • HashOperations: Data operations for map type

  • ListOperations: Data operations for list type

3. Provides a "bound" (binding) convenient operation API for keys. You can encapsulate the specified key through bound, and then perform a series of operations without "explicitly" specifying the key again, that is, BoundKeyOperations:

  • BoundValueOperations

  • BoundSetOperations

  • BoundListOperations

  • BoundSetOperations

  • BoundHashOperations

3. Use of RedisTemplate
As a template class, this class provides many APIs for quickly using redis without having to maintain connections and transactions yourself. Initially, the BaseRedisDao I created inherited from this class. The advantage of inheritance is that in each of my Dao, I can freely control the serializer and whether I need transactions. I don’t need to understand this first, just follow my current configuration method. The template provides a series of operations, such as valueOperation, HashOperation, ListOperation, SetOperation, etc., used to operate Redis of different data types. Moreover, RedisTemplate also provides the corresponding *OperationsEditor, which is used to directly inject the corresponding Operation through RedisTemplate.
Core code:

  1. package com.npf.dao.impl;

  2. ## import java.util.ArrayList;

  3. import java.util.List;

  4. import java.util.Map;

  5. import java.util.Map.Entry;

  6. ## import javax.annotation.Resource;
  7. ## import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.data.redis.core.HashOperations;
  9. import org.springframework.data.redis.core.RedisTemplate;
  10. import org.springframework.stereotype.Repository;
  11.   

  12. import com.npf.dao.StudentDao;  

  13. import com.npf.model.Student;  

  14.   

  15. @Repository  

  16. public class StudentDaoImpl implements StudentDao{  

  17.   

  18.     @Autowired  

  19.     private RedisTemplate redisTemplate;  

  20.       

  21.     @Resource(name="redisTemplate")  

  22.     private HashOperations opsForHash;  

  23.       

  24.     public static final String STUDENT = "student";  

  25.       

  26.     @Override  

  27.     public void save(Student student) {  

  28.         opsForHash.put(STUDENT, student.getId(), student);  

  29.     }  

  30.   

  31.     @Override  

  32.     public Student find(String id) {  

  33.         Student student = opsForHash.get(STUDENT, id);  

  34.         return student;  

  35.     }  

  36.   

  37.     @Override  

  38.     public void delete(String id) {  

  39.         opsForHash.delete(STUDENT, id);  

  40.     }  

  41.   

  42.     @Override  

  43.     public void update(Student student) {  

  44.         opsForHash.put(STUDENT, student.getId(), student);  

  45.     }  

  46.   

  47.     @Override  

  48.     public List findAll() {  

  49.         Map entries = opsForHash.entries(STUDENT);  

  50.         List stuList = new ArrayList();  

  51.         for(Entry entry : entries.entrySet()){  

  52.             stuList.add(entry.getValue());  

  53.         }  

  54.         return stuList;  

  55.     }  

  56. }  

控制层代码如下:

  1. package com.npf.controller;  

  2.   

  3. import java.util.List;  

  4. import java.util.UUID;  

  5.   

  6. import org.springframework.beans.factory.annotation.Autowired;  

  7. import org.springframework.stereotype.Controller;  

  8. import org.springframework.ui.Model;  

  9. import org.springframework.web.bind.annotation.RequestMapping;  

  10. import org.springframework.web.bind.annotation.RequestParam;  

  11.   

  12. import com.npf.model.Student;  

  13. import com.npf.service.StudentService;  

  14.   

  15. @Controller  

  16. public class StudentController {  

  17.   

  18.     @Autowired  

  19.     private StudentService studentService;  

  20.       

  21.     @RequestMapping("/student/save")  

  22.     public String saveStudent(Student student){  

  23.         String id = UUID.randomUUID().toString();  

  24.         System.out.println(id);  

  25.         student.setId(id);  

  26.         studentService.save(student);  

  27.         return "redirect:/student/find/all";  

  28.     }  

  29.       

  30.     @RequestMapping("/student/update")  

  31.     public String updateStudent(Student student){  

  32.         studentService.update(student);  

  33.         return "redirect:/student/find/all";  

  34.     }  

  35.       

  36.     @RequestMapping("/student/to/save/form")  

  37.     public String toSaveStudentForm(){  

  38.         return "save";  

  39.     }  

  40.       

  41.     @RequestMapping("/student/delete")  

  42.     public String deleteStudent(@RequestParam("id") String id){  

  43.         studentService.delete(id);  

  44.         return "redirect:/student/find/all";  

  45.     }  

  46.       

  47.     @RequestMapping("/student/to/update/form")  

  48.     public String toUpdateStudentForm(@RequestParam("id") String id,Model model){  

  49.         Student stu = studentService.find(id);  

  50.         model.addAttribute("stu", stu);  

  51.         return "update";  

  52.     }  

  53.       

  54.     @RequestMapping("/student/find/all")  

  55.     public String findStudents(Model model){  

  56.         List stuList = studentService.findAll();  

  57.         model.addAttribute("stuList", stuList);  

  58.         return "list";  

  59.     }  

  60. }  

The above is the detailed content of How to configure and use redis. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
es和redis区别es和redis区别Jul 06, 2019 pm 01:45 PM

Redis是现在最热门的key-value数据库,Redis的最大特点是key-value存储所带来的简单和高性能;相较于MongoDB和Redis,晚一年发布的ES可能知名度要低一些,ES的特点是搜索,ES是围绕搜索设计的。

一起来聊聊Redis有什么优势和特点一起来聊聊Redis有什么优势和特点May 16, 2022 pm 06:04 PM

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了关于redis的一些优势和特点,Redis 是一个开源的使用ANSI C语言编写、遵守 BSD 协议、支持网络、可基于内存、分布式存储数据库,下面一起来看一下,希望对大家有帮助。

实例详解Redis Cluster集群收缩主从节点实例详解Redis Cluster集群收缩主从节点Apr 21, 2022 pm 06:23 PM

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了Redis Cluster集群收缩主从节点的相关问题,包括了Cluster集群收缩概念、将6390主节点从集群中收缩、验证数据迁移过程是否导致数据异常等,希望对大家有帮助。

Redis实现排行榜及相同积分按时间排序功能的实现Redis实现排行榜及相同积分按时间排序功能的实现Aug 22, 2022 pm 05:51 PM

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了Redis实现排行榜及相同积分按时间排序,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,希望对大家有帮助。

详细解析Redis中命令的原子性详细解析Redis中命令的原子性Jun 01, 2022 am 11:58 AM

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了关于原子操作中命令原子性的相关问题,包括了处理并发的方案、编程模型、多IO线程以及单命令的相关内容,下面一起看一下,希望对大家有帮助。

实例详解Redis实现排行榜及相同积分按时间排序功能的实现实例详解Redis实现排行榜及相同积分按时间排序功能的实现Aug 26, 2022 pm 02:09 PM

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了Redis实现排行榜及相同积分按时间排序,本文通过实例代码给大家介绍的非常详细,下面一起来看一下,希望对大家有帮助。

一文搞懂redis的bitmap一文搞懂redis的bitmapApr 27, 2022 pm 07:48 PM

本篇文章给大家带来了关于redis的相关知识,其中主要介绍了bitmap问题,Redis 为我们提供了位图这一数据结构,位图数据结构其实并不是一个全新的玩意,我们可以简单的认为就是个数组,只是里面的内容只能为0或1而已,希望对大家有帮助。

redis error什么意思redis error什么意思Jun 17, 2019 am 11:07 AM

redis error就是redis数据库和其组合使用的部件出现错误,这个出现的错误有很多种,例如Redis被配置为保存数据库快照,但它不能持久化到硬盘,用来修改集合数据的命令不能用。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft