How to configure and use 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:
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
- #
-
database.properties配置文件如下:
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提供了多种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:
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;
}
}
控制层代码如下:
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";
}
}
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

1. Start the [Start] menu, enter [cmd], right-click [Command Prompt], and select Run as [Administrator]. 2. Enter the following commands in sequence (copy and paste carefully): SCconfigwuauservstart=auto, press Enter SCconfigbitsstart=auto, press Enter SCconfigcryptsvcstart=auto, press Enter SCconfigtrustedinstallerstart=auto, press Enter SCconfigwuauservtype=share, press Enter netstopwuauserv , press enter netstopcryptS

PHP function bottlenecks lead to low performance, which can be solved through the following steps: locate the bottleneck function and use performance analysis tools. Caching results to reduce recalculations. Process tasks in parallel to improve execution efficiency. Optimize string concatenation, use built-in functions instead. Use built-in functions instead of custom functions.

The caching strategy in GolangAPI can improve performance and reduce server load. Commonly used strategies are: LRU, LFU, FIFO and TTL. Optimization techniques include selecting appropriate cache storage, hierarchical caching, invalidation management, and monitoring and tuning. In the practical case, the LRU cache is used to optimize the API for obtaining user information from the database. The data can be quickly retrieved from the cache. Otherwise, the cache can be updated after obtaining it from the database.

There are performance differences between Erlang and Go. Erlang excels at concurrency, while Go has higher throughput and faster network performance. Erlang is suitable for systems that require high concurrency, while Go is suitable for systems that require high throughput and low latency.

In PHP development, the caching mechanism improves performance by temporarily storing frequently accessed data in memory or disk, thereby reducing the number of database accesses. Cache types mainly include memory, file and database cache. Caching can be implemented in PHP using built-in functions or third-party libraries, such as cache_get() and Memcache. Common practical applications include caching database query results to optimize query performance and caching page output to speed up rendering. The caching mechanism effectively improves website response speed, enhances user experience and reduces server load.

Using Redis cache can greatly optimize the performance of PHP array paging. This can be achieved through the following steps: Install the Redis client. Connect to the Redis server. Create cache data and store each page of data into a Redis hash with the key "page:{page_number}". Get data from cache and avoid expensive operations on large arrays.

First you need to set the system language to Simplified Chinese display and restart. Of course, if you have changed the display language to Simplified Chinese before, you can just skip this step. Next, start operating the registry, regedit.exe, directly navigate to HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlNlsLanguage in the left navigation bar or the upper address bar, and then modify the InstallLanguage key value and Default key value to 0804 (if you want to change it to English en-us, you need First set the system display language to en-us, restart the system and then change everything to 0409) You must restart the system at this point.

Yes, Navicat can connect to Redis, which allows users to manage keys, view values, execute commands, monitor activity, and diagnose problems. To connect to Redis, select the "Redis" connection type in Navicat and enter the server details.
