Spring Data Redis - RedisTemplate

ขณะนี้ฉันใช้ RedisTemplate จาก Spring Data Redis มีค่าเริ่มต้น StringRedisTemplate หนึ่งรายการสำหรับการดำเนินการสตริง

แต่ถ้าฉันมีวัตถุเช่น Car, CreditCard, House,....ฯลฯ ฉันควรสร้างเทมเพลต Redis หลายรายการด้วยซีเรียลไลเซอร์ที่เหมาะสมหรือไม่

RedisTemplate<String, Car>
RedisTemplate<String, CreditCard>
RedisTemplate<String, House>

การปฏิบัติที่ดีที่สุดคืออะไร?


person RamPrakash    schedule 01.07.2021    source แหล่งที่มา


คำตอบ (1)


กำหนดวัตถุ redisTemplate bean เช่นด้านล่าง spring redisTemplate ค่าเริ่มต้นของซีเรียลไลเซอร์คือ JdkSerialization คุณสามารถเปลี่ยนได้ด้วย Jackson2Json หรือ GenericJackson2Json

Jackson2Json และ GenericJackson2Json เก็บค่าเป็น json (อ่านได้)

ความแตกต่างของพวกเขาที่นี่ -› https://www.programmersought.com/article/84233376165/

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        final RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        return redisTemplate;
    }
person omer    schedule 01.07.2021
comment
ขอบคุณสำหรับคำตอบ. คุณบอกว่าเก็บทุกอย่างไว้เป็นวัตถุเหรอ? เสียประเภทไปเหรอ? - person RamPrakash; 01.07.2021
comment
คุณรู้ประเภทค่าของคีย์แล้ว สามารถใช้แบบนี้ final Car carValue = redisTemplate.opsForValue().get("carKey"); final House houseValue = redisTemplate.opsForValue().get("houseKey"); - person omer; 02.07.2021