如果需要用到Redis儲存List對象,而list又不需要進行操作,可以按照MC的方式進行存儲,不過Jedis之類的客戶端沒有提供API,可以有兩個想法實作:
1. 分別序列化 elements ,然後 set 儲存
2. 序列化List對象,set儲存
這兩種方法都類似MC的Object方法存儲,運用這種方式意味著放棄Redis對List提供的操作方法。
import net.spy.memcached.compat.CloseUtil; import net.spy.memcached.compat.log.Logger; import net.spy.memcached.compat.log.LoggerFactory; import redis.clients.jedis.Client; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * Created by IntelliJ IDEA. * User: lifeng.xu * Date: 12-6-11 * Time: 上午11:10 * To change this template use File | Settings | File Templates. */ public class JedisTest { private static Logger logger = LoggerFactory.getLogger(JedisTest.class); /** * Jedis Pool for Jedis Resource * @return */ public static JedisPool buildJedisPool(){ JedisPoolConfig config = new JedisPoolConfig(); config.setMaxActive(1); config.setMinIdle(50); config.setMaxIdle(3000); config.setMaxWait(5000); JedisPool jedisPool = new JedisPool(config, "*****", ****); return jedisPool; } /** * Test Data * @return */ public static List<User> buildTestData(){ User a = new User(); a.setName("a"); User b = new User(); b.setName("b"); List<User> list = new ArrayList<User>(); list.add(a); list.add(b); return list; } /** * Test for */ public static void testSetElements(){ List<User> testData = buildTestData(); Jedis jedis = buildJedisPool().getResource(); String key = "testSetElements" + new Random(1000).nextInt(); jedis.set(key.getBytes(), ObjectsTranscoder.serialize(testData)); //验证 byte[] in = jedis.get(key.getBytes()); List<User> list = ObjectsTranscoder.deserialize(in); for(User user : list){ System.out.println("testSetElements user name is:" + user.getName()); } } public static void testSetEnsemble(){ List<User> testData = buildTestData(); Jedis jedis = buildJedisPool().getResource(); String key = "testSetEnsemble" + new Random(1000).nextInt(); jedis.set(key.getBytes(), ListTranscoder.serialize(testData)); //验证 byte[] in = jedis.get(key.getBytes()); List<User> list = (List<User>)ListTranscoder.deserialize(in); for(User user : list){ System.out.println("testSetEnsemble user name is:" + user.getName()); } } public static void main(String[] args) { testSetElements(); testSetEnsemble(); } public static void close(Closeable closeable) { if (closeable != null) { try { closeable.close(); } catch (Exception e) { logger.info("Unable to close %s", closeable, e); } } } static class User implements Serializable{ String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } static class ObjectsTranscoder{ public static byte[] serialize(List<User> value) { if (value == null) { throw new NullPointerException("Can't serialize null"); } byte[] rv=null; ByteArrayOutputStream bos = null; ObjectOutputStream os = null; try { bos = new ByteArrayOutputStream(); os = new ObjectOutputStream(bos); for(User user : value){ os.writeObject(user); } os.writeObject(null); os.close(); bos.close(); rv = bos.toByteArray(); } catch (IOException e) { throw new IllegalArgumentException("Non-serializable object", e); } finally { close(os); close(bos); } return rv; } public static List<User> deserialize(byte[] in) { List<User> list = new ArrayList<User>(); ByteArrayInputStream bis = null; ObjectInputStream is = null; try { if(in != null) { bis=new ByteArrayInputStream(in); is=new ObjectInputStream(bis); while (true) { User user = (User) is.readObject(); if(user == null){ break; }else{ list.add(user); } } is.close(); bis.close(); } } catch (IOException e) { logger.warn("Caught IOException decoding %d bytes of data", in == null ? 0 : in.length, e); } catch (ClassNotFoundException e) { logger.warn("Caught CNFE decoding %d bytes of data", in == null ? 0 : in.length, e); } finally { CloseUtil.close(is); CloseUtil.close(bis); } return list; } } static class ListTranscoder{ public static byte[] serialize(Object value) { if (value == null) { throw new NullPointerException("Can't serialize null"); } byte[] rv=null; ByteArrayOutputStream bos = null; ObjectOutputStream os = null; try { bos = new ByteArrayOutputStream(); os = new ObjectOutputStream(bos); os.writeObject(value); os.close(); bos.close(); rv = bos.toByteArray(); } catch (IOException e) { throw new IllegalArgumentException("Non-serializable object", e); } finally { close(os); close(bos); } return rv; } public static Object deserialize(byte[] in) { Object rv=null; ByteArrayInputStream bis = null; ObjectInputStream is = null; try { if(in != null) { bis=new ByteArrayInputStream(in); is=new ObjectInputStream(bis); rv=is.readObject(); is.close(); bis.close(); } } catch (IOException e) { logger.warn("Caught IOException decoding %d bytes of data", in == null ? 0 : in.length, e); } catch (ClassNotFoundException e) { logger.warn("Caught CNFE decoding %d bytes of data", in == null ? 0 : in.length, e); } finally { CloseUtil.close(is); CloseUtil.close(bis); } return rv; } } }
PS:Redsi中儲存list沒有封裝對Object的API,是不是也是傾向於只儲存用到的字段,而不是儲存Object本身呢? Redis是一個In-Mem的產品,會覺得我們應用的方式。
更多Redis相關技術文章,請造訪Redis教學欄位學習!
以上是redis中list怎麼儲存對象的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Redisoutperformstraditionaldatabasesinspeedforread/writeOperationsDuetoitsin-memorynature,niletraditionalditionalditionalditationaldatabasesexcelcelincomplexqueriessanddaintegrity.1)redisisisisideSidealForrealForreal-timeanalyticsanticanticanticanticanticantic.2)

用戶edisinsteadofatraditionaldatabasewhenyourapplicationrequirespeedandreal-timedataprocorsing,sueAsAsforCaching,sessionmanagement,orrereal-timeanalytics.redisexcelsin:1)caching,緩存,減少載荷載量

Redis超越SQL數據庫的原因在於其高性能和靈活性。 1)Redis通過內存存儲實現極快的讀寫速度。 2)它支持多種數據結構,如列表和集合,適用於復雜數據處理。 3)單線程模型簡化開發,但高並發時可能成瓶頸。

Redis在高並發和低延遲場景下優於傳統數據庫,但不適合複雜查詢和事務處理。 1.Redis使用內存存儲,讀寫速度快,適合高並發和低延遲需求。 2.傳統數據庫基於磁盤,支持複雜查詢和事務處理,數據一致性和持久性強。 3.Redis適用於作為傳統數據庫的補充或替代,但需根據具體業務需求選擇。

Redisisahigh-performancein-memorydatastructurestorethatexcelsinspeedandversatility.1)Itsupportsvariousdatastructureslikestrings,lists,andsets.2)Redisisanin-memorydatabasewithpersistenceoptions,ensuringfastperformanceanddatasafety.3)Itoffersatomicoper

Redis主要是一個數據庫,但它不僅僅是數據庫。 1.作為數據庫,Redis支持持久化,適合高性能需求。 2.作為緩存,Redis提升應用響應速度。 3.作為消息代理,Redis支持發布-訂閱模式,適用於實時通信。

redisisamultifaceTedToolThatServesAsAdatabase,server和more.itfunctionsasanin-memorydatastrustore,supportsvariousDataStructures,and CanbeusedAsacache,MessageBroker,sessionStorage,sessionStorage,sessionstorage,andford forderibedibedlocking。

Redisisanopen-Source,內存內部的庫雷斯塔氏菌,卡赫和梅斯吉級,excellingInsPeedAndVersatory.itiswidelysusedforcaching,Real-Timeanalytics,Session Management,Session Managements,and sessighterboarderboarderboardobboardotoitsssupportfortfortfortfortfortfortfortfortorvortfortfortfortfortfortforvortfortforvortforvortforvortfortforvortforvortforvortforvortdatastherctuct anddatataCcessandcessanddataaCces


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

WebStorm Mac版
好用的JavaScript開發工具

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SublimeText3漢化版
中文版,非常好用

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境