search
HomeDatabaseRedisHow to store objects in redis

How to store objects in redis

Jun 22, 2019 pm 04:28 PM
redis

How to store objects in redis

Redis is a key-value storage system. Similar to Memcached, it supports relatively more stored value types, including string (string), list (linked list), set (set), zset (sorted set - ordered set) and hash (hash type). This article introduces For information about how Redis stores objects and collections, friends in need can refer to

Preface

Everyone knows that caching and mq message queue are two indispensable important technologies in the project. The former is mainly to reduce database pressure and greatly improve performance. The latter is mainly to improve the user experience. What I understand is an ajax request (asynchronous) made on the backend, and message queues such as ribbmitmq have retry mechanisms and other functions.

Here we mainly talk about how redis stores and retrieves objects and collections. Not much to say below, let’s take a look at the detailed introduction.

1. Add the following code to the startup class

private Jedis jedis;private JedisPoolConfig config;private JedisShardInfo sharInfo;@Beanpublic Jedis jedis(){//连接redis服务器,192.168.0.100:6379// jedis = new Jedis("192.168.0.100", 6379);// //权限认证// jedis.auth("123456");// 操作单独的文本串config = new JedisPoolConfig(); 
config.setMaxIdle(1000);//最大空闲时间config.setMaxWaitMillis(1000); //最大等待时间config.setMaxTotal(500); //redis池中最大对象个数sharInfo = new JedisShardInfo("192.168.0.100", 6379); 
sharInfo.setPassword("123456"); 
sharInfo.setConnectionTimeout(5000);//链接超时时间jedis = new Jedis(sharInfo);return jedis; 
}

2. In application.yml Add redis configuration

spring: 
 redis: 
 database: 0 
 host: 101.132.191.77 
 port: 6379 
 password: 123456 
 pool: 
 max-idle: 8 #连接池最大连接数(使用负值表示没有限制) 
 min-idle: 0 # 连接池中的最小空闲连接 
 max-active: 8 # 连接池最大阻塞等待时间(使用负值表示没有限制) 
 max-wait: -1 # 连接池中的最大空闲连接 
 timeout: 5000 # 连接超时时间(毫秒)

3. Create a new SerializeUtil class. This class is mainly used to serialize objects into redis

import java.io.ByteArrayInputStream; 
import java.io.ByteArrayOutputStream; 
import java.io.ObjectInputStream; 
import java.io.ObjectOutputStream;/** 
public class SerializeUtil 
{ 
 public static byte[] serialize(Object object) { 
 ObjectOutputStream oos = null; 
 ByteArrayOutputStream baos = null; 
 try {// 序列化baos = new ByteArrayOutputStream(); 
  oos = new ObjectOutputStream(baos); 
  oos.writeObject(object); 
  byte[] bytes = baos.toByteArray(); 
  return bytes; 
  } catch (Exception e) { 
 
  }return null; 
 } 
 public static Object unserialize( byte[] bytes) { 
 ByteArrayInputStream bais = null; 
 try { 
 // 反序列化bais = new ByteArrayInputStream(bytes); 
 ObjectInputStream ois = new ObjectInputStream(bais); 
 return ois.readObject(); 
  } catch (Exception e) { 
 
  }return null; 
 } 
 }

4. I encapsulated a RedisServiceImpl class, mainly used to set and get values ​​for redis

import com.ys.util.redis.SerializeUtil; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.data.redis.core.StringRedisTemplate; 
import org.springframework.stereotype.Service; 
import redis.clients.jedis.Jedis; 
import java.util.List; 
import java.util.Map; 
import java.util.concurrent.TimeUnit; 
@Service 
public class RedisServiceImpl 
 
 {@Autowired 
 
 private StringRedisTemplate stringRedisTemplate; 
 @Autowired 
 private Jedis jedis; 
 public void setStr(String key, String value) { 
 setStr(key, value, null); 
 } 
 public void setStr(String key, Object value, Long time) 
 {if(value == null){ 
 return; 
 }if(value instanceof String){ 
 String obj = (String) value; 
 stringRedisTemplate.opsForValue().set(key, obj); 
 }else if(value instanceof List){ 
 List obj = (List) value; 
 stringRedisTemplate.opsForList().leftPushAll(key,obj); 
 }else if(value instanceof Map){ 
 Map obj = (Map) value; 
 stringRedisTemplate.opsForHash().putAll(key,obj); 
 }if (time != null) 
 stringRedisTemplate.expire(key, time, TimeUnit.SECONDS); 
 } 
 public Object getKey(String key) 
 {return stringRedisTemplate.opsForValue().get(key); 
  } 
 public void delKey(String key) { 
 stringRedisTemplate.delete(key); 
 } 
 public boolean del(String key) 
 {return jedis.del(key.getBytes())>0; 
 } 
}

5. Test whether redis is ok and write the redisController class

import com.ys.service.impl.RedisServiceImpl; 
import com.ys.vo.IqProduct; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RestController; 
import java.util.ArrayList; 
import java.util.Date; 
import java.util.List; 
@RestController 
 
public class RedisServiceController 
 
 { 
@Autowired 
 
private RedisServiceImpl redisService; 
@RequestMapping(value = "/setredis") 
public String setredis(String keyredis){ 
 redisService.setStr(keyredis,"2018年1月26日"); 
 return "保存成功,请访问getredis查询redis"; 
} 
@RequestMapping(value = "/setObj") 
public String setObj(String keyredis){ 
 IqProduct iqProduct = new IqProduct(); 
 iqProduct.setSort(1); 
 iqProduct.setTimestamp(new Date().getTime()); 
 iqProduct.setProductName("productname"); 
 // list.add(iqProduct); 
 redisService.set(keyredis, iqProduct); 
 return "保存成功,请访问getredis查询redis"; 
 } 
 @RequestMapping(value = "/getObj") 
 public Object getObj(String keyredis){ 
 Object object = redisService.get(keyredis); 
 if(object !=null){ 
 IqProduct iqProduct = (IqProduct) object; 
 System. out.println(iqProduct.getProductName()); 
 System. out.println(iqProduct.getId()); 
 System. out.println(iqProduct.getTimestamp()); 
 }return object; 
} 
 @RequestMapping(value = "/delObj") 
 public boolean delObj(String keyredis) 
 {boolean del = redisService.del(keyredis); 
  return del; 
 } 
 @RequestMapping(value = "/getredis") 
 public String getredis(String keyredis){ 
 String getredis = (String) redisService.getKey(keyredis); 
 return "redis的key是===>"+getredis; 
 } 
 @RequestMapping(value = "/delredis") 
 public String delredis(String keyredis){ 
 redisService.delKey(keyredis); 
 return "删除成功,请通过getredis进行查询"; 
 } 
 @RequestMapping(value = "/setList") 
 public String setList(String keyredis){ 
 List list = new ArrayList();for (int i = 0;i<10;i++){ 
 IqProduct iqProduct = new IqProduct(); 
 iqProduct.setSort(1); 
 iqProduct.setTimestamp(new Date().getTime()); 
 iqProduct.setProductName("productname"); 
 list.add(iqProduct); 
 } 
 redisService.set(keyredis, list); 
 return "保存成功,请访问getredis查询redis"; 
 } 
 @RequestMapping(value = "/getList") 
 public Object getList(String keyredis){ 
 Object object = redisService.get(keyredis); 
 if(object !=null){ 
 List<IqProduct> iqProducts = (List<IqProduct>) object; 
 for (int i = 0;i<iqProducts.size();i++){ 
 IqProduct iqProduct = iqProducts.get(i); 
 System. out.println(iqProduct.getProductName()); 
 System. out.println(iqProduct.getId()); 
 System. out.println(iqProduct.getTimestamp()); 
 } 
 }return object; 
 } 
 @RequestMapping(value = "/delList") 
 public boolean delList(String keyredis) 
 { 
 boolean del = redisService.del(keyredis);return del; 
 } 
}

6. Test results

How to store objects in redis

##For more Redis related technical articles, please visit Redis Tutorial column to learn!

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

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Redis: Exploring Its Features and FunctionalityRedis: Exploring Its Features and FunctionalityApr 19, 2025 am 12:04 AM

Redis stands out because of its high speed, versatility and rich data structure. 1) Redis supports data structures such as strings, lists, collections, hashs and ordered collections. 2) It stores data through memory and supports RDB and AOF persistence. 3) Starting from Redis 6.0, multi-threaded I/O operations have been introduced, which has improved performance in high concurrency scenarios.

Is Redis a SQL or NoSQL Database? The Answer ExplainedIs Redis a SQL or NoSQL Database? The Answer ExplainedApr 18, 2025 am 12:11 AM

RedisisclassifiedasaNoSQLdatabasebecauseitusesakey-valuedatamodelinsteadofthetraditionalrelationaldatabasemodel.Itoffersspeedandflexibility,makingitidealforreal-timeapplicationsandcaching,butitmaynotbesuitableforscenariosrequiringstrictdataintegrityo

Redis: Improving Application Performance and ScalabilityRedis: Improving Application Performance and ScalabilityApr 17, 2025 am 12:16 AM

Redis improves application performance and scalability by caching data, implementing distributed locking and data persistence. 1) Cache data: Use Redis to cache frequently accessed data to improve data access speed. 2) Distributed lock: Use Redis to implement distributed locks to ensure the security of operation in a distributed environment. 3) Data persistence: Ensure data security through RDB and AOF mechanisms to prevent data loss.

Redis: Exploring Its Data Model and StructureRedis: Exploring Its Data Model and StructureApr 16, 2025 am 12:09 AM

Redis's data model and structure include five main types: 1. String: used to store text or binary data, and supports atomic operations. 2. List: Ordered elements collection, suitable for queues and stacks. 3. Set: Unordered unique elements set, supporting set operation. 4. Ordered Set (SortedSet): A unique set of elements with scores, suitable for rankings. 5. Hash table (Hash): a collection of key-value pairs, suitable for storing objects.

Redis: Classifying Its Database ApproachRedis: Classifying Its Database ApproachApr 15, 2025 am 12:06 AM

Redis's database methods include in-memory databases and key-value storage. 1) Redis stores data in memory, and reads and writes fast. 2) It uses key-value pairs to store data, supports complex data structures such as lists, collections, hash tables and ordered collections, suitable for caches and NoSQL databases.

Why Use Redis? Benefits and AdvantagesWhy Use Redis? Benefits and AdvantagesApr 14, 2025 am 12:07 AM

Redis is a powerful database solution because it provides fast performance, rich data structures, high availability and scalability, persistence capabilities, and a wide range of ecosystem support. 1) Extremely fast performance: Redis's data is stored in memory and has extremely fast read and write speeds, suitable for high concurrency and low latency applications. 2) Rich data structure: supports multiple data types, such as lists, collections, etc., which are suitable for a variety of scenarios. 3) High availability and scalability: supports master-slave replication and cluster mode to achieve high availability and horizontal scalability. 4) Persistence and data security: Data persistence is achieved through RDB and AOF to ensure data integrity and reliability. 5) Wide ecosystem and community support: with a huge ecosystem and active community,

Understanding NoSQL: Key Features of RedisUnderstanding NoSQL: Key Features of RedisApr 13, 2025 am 12:17 AM

Key features of Redis include speed, flexibility and rich data structure support. 1) Speed: Redis is an in-memory database, and read and write operations are almost instantaneous, suitable for cache and session management. 2) Flexibility: Supports multiple data structures, such as strings, lists, collections, etc., which are suitable for complex data processing. 3) Data structure support: provides strings, lists, collections, hash tables, etc., which are suitable for different business needs.

Redis: Identifying Its Primary FunctionRedis: Identifying Its Primary FunctionApr 12, 2025 am 12:01 AM

The core function of Redis is a high-performance in-memory data storage and processing system. 1) High-speed data access: Redis stores data in memory and provides microsecond-level read and write speed. 2) Rich data structure: supports strings, lists, collections, etc., and adapts to a variety of application scenarios. 3) Persistence: Persist data to disk through RDB and AOF. 4) Publish subscription: Can be used in message queues or real-time communication systems.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools