1. 程式人生 > 程式設計 >一文解析redis如何儲存物件和集合

一文解析redis如何儲存物件和集合

在專案中,快取以及mq訊息佇列可以說是不可或缺的2個重要技術。前者主要是為了減輕資料庫壓力,大幅度提升效能。後者主要是為了提高使用者的體驗度,我理解的是再後端做的一個ajax請求(非同步),並且像ribbmitmq等訊息佇列有重試機制等功能。

這裡主要講redis如何把物件,集合存入,並且取出.

1.在啟動類上加入如下程式碼

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.在application.yml當中加入redis配置

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..新建SerializeUtil類,這個類主要是為了將物件序列化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.我封裝了一個RedisServiceImpl類,主要是用對redis設值和取值

redisServiceImpl.set主要是傳object,setStr主要設定string

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.測試redis是否ok,編寫redisController類

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.測試結果