Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How redis stores objects

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces how to store objects in redis. It is very detailed and has a certain reference value. Friends who are interested must read it!

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

Preface

We all know that caching and mq message queuing are two important technologies that are indispensable in a project. The former is mainly to reduce the pressure on the database and greatly improve the performance. The latter is mainly to improve the user's experience. What I understand is an ajax request (asynchronous) made at the back end, and message queues such as ribbmitmq have functions such as retry mechanism.

Here we mainly talk about how redis stores and removes objects and collections. There is no more 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 () {/ / Connect to the redis server, 192.168.0.100 jedis 6379 / jedis = new Jedis ("192.168.0.100", 6379); / permission authentication / / jedis.auth ("123456"); / / operate a separate text string config = new JedisPoolConfig (); config.setMaxIdle (1000); / / maximum idle time config.setMaxWaitMillis (1000) / / maximum waiting time config.setMaxTotal; / / maximum number of objects in the redis pool sharInfo = new JedisShardInfo ("192.168.0.100", 6379); sharInfo.setPassword ("123456"); sharInfo.setConnectionTimeout (5000); / / Link timeout jedis = new Jedis (sharInfo); return jedis;}

two。 Add redis configuration to application.yml

Spring: redis: database: 0 host: 101.132.191.77 port: 6379 password: 123456 pool: max-idle: 8 # connection pool maximum number of connections (using negative values for no limit) min-idle: 0 # minimum idle connections in the connection pool max-active: 8 # connection pool maximum blocking wait time (using negative values for unlimited) max-wait:-1 # maximum connection pool Idle connection timeout: 5000 # connection timeout (milliseconds)

3. Create a new SerializeUtil class, which is mainly used to serialize objects in 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 {/ / Serialization 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 {/ / deserialization bais = new ByteArrayInputStream (bytes); ObjectInputStream ois = new ObjectInputStream (bais); return ois.readObject ();} catch (Exception e) {} return null;}}

4. I encapsulated a RedisServiceImpl class, which is mainly used to set and take 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 redisController classes

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, 26 January 2018) Return "saved successfully, please visit getredis to query 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 "saved successfully, please visit getredis query 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 is = = >" + getredis;} @ RequestMapping (value = "/ delredis") public String delredis (String keyredis) {redisService.delKey (keyredis) Return "deleted successfully, please query via getredis";} @ RequestMapping (value = "/ setList") public String setList (String keyredis) {List list = new ArrayList (); for (int I = 0 Testi

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.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report