redis配置及常用方法封装

1、在启动类插入一下代码

private Jedis jedis;

	private JedisPoolConfig config;

	private JedisShardInfo sharInfo;
	@Bean
	public 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("127.0.0.1", 6379);
//		sharInfo.setPassword("123456");
		sharInfo.setConnectionTimeout(5000);//链接超时时间
		jedis = new Jedis(sharInfo);
		return jedis;
	}

 

 

2.在application.yml当中加入redis配置

#redis配置
redis:
#  数据库索引
  database: 0
#    服务器地址
  host: 127.0.0.1
#    服务器连接端口
  port: 6379
#    链接密码
  password:
#    链接池
  pool:
#    最大连接数(负值表示没有限制)
    max-active: 8
#      最大阻塞等待时间(负值表示没有限制)
    max-wait: 1
#      最大空闲链接
    max-idle: 8
#      最小空闲链接
    min-idle: 0
#    链接超时时间(毫秒)
    timeout: 0

3.新建SerializeUtil类,这个类主要是为了将对象序列化redis当中

package com.dse.demo.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.封装一个RedisService类,用于常用方法

package com.dse.demo.redis;

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 RedisService {

    @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);
    }





    /**set Object*/
    public String set(String key,Object object)
    {
//        Jedis jedis=new Jedis();
        return jedis.set(key.getBytes(), SerializeUtil.serialize(object));
    }

    /**get Object*/
    public Object get(String key)
    {
//        Jedis jedis=new Jedis();
        byte[] value = jedis.get(key.getBytes());
        return SerializeUtil. unserialize(value);
    }

    /**delete a key**/
    public boolean del(String key)
    {
//        Jedis jedis=new Jedis();
        return jedis.del(key.getBytes())>0;
    }

}

5.设计 RedisController 层,检测数据

package com.dse.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dse.demo.domain.entity.HcmOutEmpTemp;
import com.dse.demo.redis.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/redis")
public class RedisController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisService redisService;

    @RequestMapping("/savedf")
    @ResponseBody
    public void saveRedis(){
        List list=new ArrayList();
        list.add("222");
        list.add("223");
        list.add("224");
        list.add("225");
        list.add("226");
        String str=JSON.toJSONString(list);

        stringRedisTemplate.opsForValue().set("dff",str);
    }

    @RequestMapping("/get")
    @ResponseBody
    public List get(){
        String df=stringRedisTemplate.opsForValue().get("dff");
        List rt=JSONObject.parseArray(df);
        return rt;
    }

    @RequestMapping(value = "/setredis")
    @ResponseBody
    public String setredis(String keyredis){
        redisService.setStr(keyredis,"2018年1月26日");
        return "保存成功,请访问getredis查询redis";
    }

    @RequestMapping(value = "/setObj")
    @ResponseBody
    public String setObj(String keyredis){
        HcmOutEmpTemp iqProduct = new HcmOutEmpTemp();
        iqProduct.setEmpId(1L);
        iqProduct.setSfDate(new Date());
        iqProduct.setAbkrs("xdddd");
// list.add(iqProduct);
        redisService.set(keyredis, iqProduct);
        return "保存成功,请访问getredis查询redis";
    }

    @RequestMapping(value = "/getObj")
    @ResponseBody
    public Object getObj(String keyredis){
        Object object = redisService.get(keyredis);
        if(object !=null){
            HcmOutEmpTemp iqProduct = (HcmOutEmpTemp) object;
            System. out.println(iqProduct.getEmpId());
            System. out.println(iqProduct.getSfDate());
            System. out.println(iqProduct.getAbkrs());
        }
        return object;
    }

    @RequestMapping(value = "/delObj")
    @ResponseBody
    public boolean delObj(String keyredis){
        boolean del = redisService.del(keyredis);
        return del;
    }


    @RequestMapping(value = "/getredis")
    @ResponseBody
    public String getredis(String keyredis){
        String getredis = (String) redisService.getKey(keyredis);
        return "redis的key是===>"+getredis;
    }


    @RequestMapping(value = "/delredis")
    @ResponseBody
    public String delredis(String keyredis){
        redisService.delKey(keyredis);
        return "删除成功,请通过getredis进行查询";
    }





    @RequestMapping(value = "/setList")
    @ResponseBody
    public String setList(String keyredis){
        List list = new ArrayList();
        for (int i = 0;i<10;i++){
            HcmOutEmpTemp iqProduct = new HcmOutEmpTemp();
            iqProduct.setEmpId(1L);
            iqProduct.setSfDate(new Date());
            iqProduct.setAbkrs("xdddd");
            list.add(iqProduct);
        }
        redisService.set(keyredis, list);
        return "保存成功,请访问getredis查询redis";
    }

    @RequestMapping(value = "/getList")
    @ResponseBody
    public Object getList(String keyredis){
        Object object = redisService.get(keyredis);
        if(object !=null){
            List iqProducts = (List) object;
            for (int i = 0;i

 

 

你可能感兴趣的:(Redis)