redis&&Jedis实测记录

准备工具redis.exe,RedisDesktopManager

链接:https://pan.baidu.com/s/1szSoEiGFbyNA2Zmm9gBKVA 
提取码:43qt

pom

  <!-- redis依赖包 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>

        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.37</version>
        </dependency>
        <!--解析json数组对象字符串与将map转对象-->
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
        </dependency>
        <!--map转对象-->
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.2</version>
            <scope>compile</scope>
        </dependency>
        <!-- redis连接池 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

配置文件

spring:
  redis:
    # Redis数据库索引(默认为 0)
    database: 0
    # Redis服务器地址
    host: 127.0.0.1
    # Redis服务器连接端口
    port: 6379
    # Redis 密码
    password:  
    lettuce:
      pool:
        # 连接池中的最小空闲连接
        min-idle: 8
        # 连接池中的最大空闲连接
        max-idle: 500
        # 连接池最大连接数(使用负值表示没有限制)
        max-active: 2000
        # 连接池最大阻塞等待时间(使用负值表示没有限制)
        max-wait: 10000
    # 连接超时时间(毫秒)
    timeout: 5000

redis配置类

package com.springboot.redis.common.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
 
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
 
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;

/**
 * Redis缓存配置类
 * @author
 *
 */
@Configuration
@EnableCaching//开启注解
public class RedisConfig extends CachingConfigurerSupport {

    /**
     * 自定义key
     * @return
     */
    @Override
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object o, Method method, Object... objects) {
                //格式化
                StringBuilder sb = new StringBuilder();
                sb.append(o.getClass().getName());
                sb.append(method.getName());
                for (Object obj : objects) {
                    sb.append(obj.toString());
                }
                System.out.println("调用redis缓存key:" + sb.toString());
                return sb.toString();
            }
        };
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisCacheManager cacheManager = RedisCacheManager.create(factory);
        return cacheManager;
    }


    @Bean
    @ConditionalOnClass(RedisOperations.class)
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);

        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.activateDefaultTyping(mapper.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(mapper);

        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // key采用 String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        // hash的 key也采用 String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        // value序列化方式采用 jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // hash的 value序列化方式采用 jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();

        return template;
    }
}

redis服务层

package com.springboot.redis.common.service;/**
 * @author Mr伍
 * @date 2020/9/9 17:39
 */

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 * @ClassName: IRedisService
 * @Auther: Mr伍
 * @Date: 2020/09/09/17:39
 */
public interface IRedisService {
    Boolean expire(String key, Long time);
    Long getExpire(String key);
    Boolean hasKey(String key);
    void   del(String... key);
    Object get(String key);
    Boolean set(String key, Object value);
    Boolean set(String key, Object value, Long time);
    Long incr(String key, Long delta);
    Long decr(String key, Long delta);
    Object hget(String key, String item);
    Map<Object, Object> hmget(String key);
    Boolean hmset(String key, Map<String, Object> map);
    Boolean hmset(String key, Map<String, Object> map, Long time);
    Boolean hset(String key, String item, Object value);
    Boolean hset(String key, String item, Object value, Long time);
    void hdel(String key, Object... item);
    Boolean hHasKey(String key, String item);
    Double hincr(String key, String item, Double by);
    Double hdecr(String key, String item, Double by);
    Set<Object> sGet(String key);
    Boolean sHasKey(String key, Object value);
    Long sSet(String key, Object... values);
    Long sSetAndTime(String key, Long time, Object... values);
    Long sGetSetSize(String key);
    Long setRemove(String key, Object... values);
    List<Object> lGet(String key, Long start, Long end);
    Long lGetListSize(String key);
    Object lGetIndex(String key, Long index);
    Boolean lSetO(String key, Object value);
    Boolean lSetO(String key, Object value, Long time);
    Boolean lSet(String key, List<Object> value);
    Boolean lSet(String key, List<Object> value, Long time);
    Boolean lUpdateIndex(String key, Long index, Object value);
    Long lRemove(String key, Long count, Object value);

}

package com.springboot.redis.common.service.impl;

import com.springboot.redis.common.service.IRedisService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 定义常用的 Redis操作
 *
 */
@Service
public class RedisServiceImpl implements IRedisService {

    @Resource
    private  RedisTemplate<String, Object> redisTemplate;

    /**
     * 指定缓存失效时间
     *
     * @param key  键
     * @param time 时间(秒)
     * @return Boolean
     */
    @Override
    public Boolean expire(String key, Long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据key获取过期时间
     *
     * @param key 键 不能为 null
     * @return 时间(秒) 返回 0代表为永久有效
     */
    @Override
    public Long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    /**
     * 判断 key是否存在
     *
     * @param key 键
     * @return true 存在 false不存在
     */
    @Override
    public Boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除缓存
     *
     * @param key 可以传一个值 或多个
     */
    @Override
    public void del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete(Arrays.asList(key));
            }
        }
    }

    /**
     * 普通缓存获取
     *
     * @param key 键
     * @return 值
     */
    @Override
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * 普通缓存放入
     *
     * @param key   键
     * @param value 值
     * @return true成功 false失败
     */
    @Override
    public Boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 普通缓存放入并设置时间
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期
     * @return true成功 false 失败
     */
    @Override
    public Boolean set(String key, Object value, Long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 递增
     *
     * @param key   键
     * @param delta 要增加几(大于0)
     * @return Long
     */
    @Override
    public Long incr(String key, Long delta) {
        if (delta < 0) {
            throw new RuntimeException("递增因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, delta);
    }

    /**
     * 递减
     *
     * @param key   键
     * @param delta 要减少几
     * @return Long
     */
    @Override
    public Long decr(String key, Long delta) {
        if (delta < 0) {
            throw new RuntimeException("递减因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, -delta);
    }

    /**
     * HashGet
     *
     * @param key  键 不能为 null
     * @param item 项 不能为 null
     * @return 值
     */
    @Override
    public Object hget(String key, String item) {
        return redisTemplate.opsForHash().get(key, item);
    }

    /**
     * 获取 hashKey对应的所有键值
     *
     * @param key 键
     * @return 对应的多个键值
     */
    @Override
    public Map<Object, Object> hmget(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * HashSet
     *
     * @param key 键
     * @param map 对应多个键值
     * @return true 成功 false 失败
     */
    @Override
    public Boolean hmset(String key, Map<String, Object> map) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * HashSet 并设置时间
     *
     * @param key  键
     * @param map  对应多个键值
     * @param time 时间(秒)
     * @return true成功 false失败
     */
    @Override
    public Boolean hmset(String key, Map<String, Object> map, Long time) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @return true 成功 false失败
     */
    @Override
    public Boolean hset(String key, String item, Object value) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @param time  时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
     * @return true 成功 false失败
     */
    @Override
    public Boolean hset(String key, String item, Object value, Long time) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除hash表中的值
     *
     * @param key  键 不能为 null
     * @param item 项 可以使多个不能为 null
     */
    @Override
    public void hdel(String key, Object... item) {
        redisTemplate.opsForHash().delete(key, item);
    }

    /**
     * 判断hash表中是否有该项的值
     *
     * @param key  键 不能为 null
     * @param item 项 不能为 null
     * @return true 存在 false不存在
     */
    @Override
    public Boolean hHasKey(String key, String item) {
        return redisTemplate.opsForHash().hasKey(key, item);
    }

    /**
     * hash递增 如果不存在,就会创建一个 并把新增后的值返回
     *
     * @param key  键
     * @param item 项
     * @param by   要增加几(大于0)
     * @return Double
     */
    @Override
    public Double hincr(String key, String item, Double by) {
        return redisTemplate.opsForHash().increment(key, item, by);
    }

    /**
     * hash递减
     *
     * @param key  键
     * @param item 项
     * @param by   要减少记(小于0)
     * @return Double
     */
    @Override
    public Double hdecr(String key, String item, Double by) {
        return redisTemplate.opsForHash().increment(key, item, -by);
    }

    /**
     * 根据 key获取 Set中的所有值
     *
     * @param key 键
     * @return Set
     */
    @Override
    public Set<Object> sGet(String key) {
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据value从一个set中查询,是否存在
     *
     * @param key   键
     * @param value 值
     * @return true 存在 false不存在
     */
    @Override
    public Boolean sHasKey(String key, Object value) {
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将数据放入set缓存
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 成功个数
     */
    @Override
    public Long sSet(String key, Object... values) {
        try {
            return redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            e.printStackTrace();
            return 0L;
        }
    }

    /**
     * 将set数据放入缓存
     *
     * @param key    键
     * @param time   时间(秒)
     * @param values 值 可以是多个
     * @return 成功个数
     */
    @Override
    public Long sSetAndTime(String key, Long time, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().add(key, values);
            if (time > 0) {
                expire(key, time);
            }
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0L;
        }
    }

    /**
     * 获取set缓存的长度
     *
     * @param key 键
     * @return Long
     */
    @Override
    public Long sGetSetSize(String key) {
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0L;
        }
    }

    /**
     * 移除值为value的
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 移除的个数
     */
    @Override
    public Long setRemove(String key, Object... values) {
        try {
            return redisTemplate.opsForSet().remove(key, values);
        } catch (Exception e) {
            e.printStackTrace();
            return 0L;
        }
    }

    /**
     * 获取list缓存的内容
     *
     * @param key   键
     * @param start 开始
     * @param end   结束 0 到 -1代表所有值
     * @return List
     */
    @Override
    public List<Object> lGet(String key, Long start, Long end) {
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取list缓存的长度
     *
     * @param key 键
     * @return Long
     */
    @Override
    public Long lGetListSize(String key) {
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0L;
        }
    }

    /**
     * 通过索引 获取list中的值
     *
     * @param key   键
     * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;
     *              index<0时,-1,表尾,-2倒数第二个元素,依次类推
     * @return Object
     */
    @Override
    public Object lGetIndex(String key, Long index) {
        try {
            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @return Boolean
     */
    @Override
    public Boolean lSetO(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return Boolean
     */
    @Override
    public Boolean lSetO(String key, Object value, Long time) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @return Boolean
     */
    @Override
    public Boolean lSet(String key, List<Object> value) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return Boolean
     */
    @Override
    public Boolean lSet(String key, List<Object> value, Long time) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据索引修改list中的某条数据
     *
     * @param key   键
     * @param index 索引
     * @param value 值
     * @return Boolean
     */
    @Override
    public Boolean lUpdateIndex(String key, Long index, Object value) {
        try {
            redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 移除N个值为value
     *
     * @param key   键
     * @param count 移除多少个
     * @param value 值
     * @return 移除的个数
     */
    @Override
    public Long lRemove(String key, Long count, Object value) {
        try {
            return redisTemplate.opsForList().remove(key, count, value);
        } catch (Exception e) {
            e.printStackTrace();
            return 0L;
        }
    }
}

测试类

package com.springboot.redis;/**
 * @author Mr伍
 * @date 2020/9/11 11:07
 */
import com.springboot.redis.common.service.IRedisService;
import com.springboot.redis.model.Swagger2;
import com.springboot.redis.utils.JsonStringToObjectUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.beanutils.BeanUtils;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * @ClassName: RedisListSetGetTest
 * @Auther: Mr伍
 * @Date: 2020/09/11/11:07
 */

@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisListSetGetTest {



    @Autowired
    private IRedisService iRedisService;

    @Test
    public  void listSetValue() {
        Swagger2 swagger2=new Swagger2();
        swagger2.setName("测试");
        List<Swagger2> list=new ArrayList<>();
        list.add(swagger2);
        Boolean b= iRedisService.lSet("entity", Collections.singletonList(list));
        System.err.println(b);
    }
/**
 * @Author Mr伍
 * @Description //TODO 获取当前key值下的所有的list集合对象Map 再将map转换成对象。
 * @Date  2020/9/11
 * @Param []
 * @return void
 **/
    @Test
    public void getListValue() throws InvocationTargetException, IllegalAccessException {
        List<Map> user2 =(ArrayList)iRedisService.lGet("entity",0L,-1L);
        if(user2==null||user2.size()==0){
            Swagger2 swagger2=new Swagger2();
            swagger2.setAge(23);
            swagger2.setName("伍柳");
            List<Swagger2> list1=new ArrayList<>();
            list1.add(swagger2);
            Boolean b=  iRedisService.lSet("entity", Collections.singletonList(list1));//   .opsForValue().set("user1", swagger2);
            System.out.println(b+"__redis中没有值:");
            if(b){
                System.err.println("成功存入缓存对象:"+swagger2);
            }
        }else {
            for (int i = 0; i < user2.size(); i++) {
                System.err.println(user2.get(i));
                JSONArray jsonArray = JSONArray.fromObject(user2.get(i));
                for (int j = 0; j < jsonArray.size(); j++) {
                    JSONObject jsonObject = JSONObject.fromObject(jsonArray.get(j));
                    Map map = (Map) JSONObject.toBean(jsonObject, Map.class);
                    Swagger2 swagger2=new Swagger2();
                    BeanUtils.populate(swagger2,map);
                    System.err.println(swagger2);
                }
            }
            System.err.println("成功获取到值");
        }
    }
    /**
     * @Author Mr伍
     * @Description //TODO 若返回的全是Map类型
     * @Date  2020/9/14
     * @Param []
     * @return void
     **/
    public void tesOne() throws InvocationTargetException, IllegalAccessException {
        List<List<Map>> list =(ArrayList)iRedisService.lGet("entity",0L,-1L);
        List<Map<String,Object>> mapList= JsonStringToObjectUtil.getObject(list,new Swagger2());
        System.err.println(mapList);
        mapList.forEach(i->{
            try {
                Swagger2 swagger2=new Swagger2();
                //Map转对象
                BeanUtils.populate(swagger2,i);
                System.err.println(swagger2);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        });

    }


/**
 * @Author Mr伍
 * @Description //TODO 最终版(config配置为返回类型)
 * @Date  2020/9/11
 * @Param []
 * @return void
 **/
    @Test
    public void getUtils(){
        List<List<Swagger2>> list =(ArrayList)iRedisService.lGet("entity",0L,-1L);
        list.forEach(i->{
            i.forEach(j->{
            System.err.println(j);

            });
        });


    }







}

测试k,v

package com.springboot.redis;/**
 * @author Mr伍
 * @date 2020/9/11 11:05
 */

import com.springboot.redis.common.service.IRedisService;
import com.springboot.redis.model.Swagger2;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * Created with IntelliJ IDEA.
 * @ClassName: RedisSetTest
 * @Auther: Mr伍
 * @Date: 2020/09/11/11:05
 */


@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisSetTest {

    @Autowired
    private IRedisService iRedisService;
    @Test
    public void setObjectValue(){
        Swagger2 swagger2 =new Swagger2();
        swagger2.setName("设置单一值对象5");
      boolean b=  iRedisService.set("obj",swagger2);
        if(b){
            System.err.println("存入成功");
            Swagger2 swagger21=(Swagger2) iRedisService.get("obj");
            System.err.println(swagger21);
        }


    }




}

Jedis自定义配置文件

#redis
wl.redis.host=127.0.0.1
wl.redis.port=6379
wl.redis.password= 
wl.redis.timeout=5000
wl.redis.poolMaxTotal=10
wl.redis.poolMaxIdle=3
wl.reids.poolMaxWait=5000
wl.redis.db=1

配置类

package com.springboot.redis.common.properties;/**
 * @author Mr伍
 * @date 2020/9/11 17:23
 */

import lombok.Data;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
 
@Data
@SpringBootConfiguration
@PropertySource(value = {"classpath:wl.properties"})
@ConfigurationProperties(prefix = "wl")
public class WlProperties {
  private RedisProperties redis=new RedisProperties();


}

package com.springboot.redis.common.properties;/**
 * @author Mr伍
 * @date 2020/9/11 17:42
 */

import lombok.Data;

/**
 * Created with IntelliJ IDEA.
 * @ClassName: RedisProperties
 * @Auther: Mr伍
 * @Date: 2020/09/11/17:42
 */
@Data
public class RedisProperties {

    private String host;
    private int port;
    private String password;
    private int timeout;
    private int poolMaxTotal;
    private int poolMaxIdle;
    private int poolMaxWait;
    private int db;

}

package com.springboot.redis.common.config;/**
 * @author Mr伍
 * @date 2020/9/11 16:19
 */

import com.springboot.redis.common.properties.WlProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Created with IntelliJ IDEA.
 * @ClassName: JedisPoolFactory
 * @Auther: Mr伍
 * @Date: 2020/09/11/16:19
 */
/**
 *创建RedisPool对象
 */
@Component
public class JedisPoolFactory {

        @Autowired
        private WlProperties wlProperties;

        @Bean
        public JedisPool getJedisPool(){
            JedisPoolConfig jedisPoolConfig=new JedisPoolConfig();
            jedisPoolConfig.setMaxIdle(wlProperties.getRedis().getPoolMaxIdle());
            jedisPoolConfig.setMaxWaitMillis(wlProperties.getRedis().getPoolMaxWait());
            jedisPoolConfig.setMaxTotal(wlProperties.getRedis().getPoolMaxTotal());
            JedisPool jp=new JedisPool(jedisPoolConfig,wlProperties.getRedis().getHost(),wlProperties.getRedis().getPort(),
                    wlProperties.getRedis().getTimeout(),wlProperties.getRedis().getPassword(),wlProperties.getRedis().getDb());
            return jp;
        }

}

服务层

package com.springboot.redis.common.service.impl;/**
 * @author Mr伍
 * @date 2020/9/11 17:46
 */
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * Created with IntelliJ IDEA.
 * @ClassName: JedisServiceImpl
 * @Auther: Mr伍
 * @Date: 2020/09/11/17:46
 */
@Service
public class JedisServiceImpl {


    /**
     * 通过Jedis操作Redis
     */
        @Autowired
        JedisPool jedisPool;

        /**
         * 获取对象
         * @param key
         * @param clazz
         * @param <T>
         * @return
         */
        public <T> T get(String key, Class<T> clazz) {
            Jedis jedis = null;
            try {
                jedis = jedisPool.getResource();
                String str = jedis.get(key);
                T t = stringToBean(str, clazz);
                return t;
            }finally {
                closeJedis(jedis);
            }
        }

        /**
         * 设置对象
         * @param key
         * @param value
         * @param <T>
         * @return
         */
        public <T> boolean set(String key,T value){
            Jedis jedis=null;
            try {
                jedis=jedisPool.getResource();
                String str=beanToString(value);
                if (str==null||str.length()<=0){
                    return false;
                }
                jedis.set(key,str);
                return true;
            }finally {
                closeJedis(jedis);
            }
        }

        /**
         * 删除
         * @param key
         * @return
         */
        public boolean delete(String key){
            Jedis jedis=null;
            try{
                jedis=jedisPool.getResource();
                long ret=jedis.del(key);
                return ret>0;
            }finally {
                closeJedis(jedis);
            }
        }

        /**
         * 判断key是否存在
         * @param key
         * @param <T>
         * @return
         */
        public <T> boolean exists(String key){
            Jedis jedis=null;
            try{
                jedis=jedisPool.getResource();
                return jedis.exists(key);
            }finally {
                closeJedis(jedis);
            }
        }

        /**
         * 增加值
         * @param key
         * @param <T>
         * @return
         */
        public<T> Long incr(String key){
            Jedis jedis=null;
            try{
                jedis=jedisPool.getResource();
                return jedis.incr(key);
            }finally {
                closeJedis(jedis);
            }
        }

        /**
         * 减少值
         * @param key
         * @param <T>
         * @return
         */
        public<T> Long decr(String key){
            Jedis jedis=null;
            try{
                jedis=jedisPool.getResource();
                return jedis.decr(key);
            }finally {
                closeJedis(jedis);
            }
        }

        /**
         * 关闭jedis
         * @param jedis
         */
        private void closeJedis(Jedis jedis) {//用完记得要关闭
            if (jedis != null) {
                jedis.close();
            }
        }

        /**
         * 将String转换为其他对象
         *
         * @param str
         * @param clazz
         * @param <T>
         * @return
         */
        private <T> T stringToBean(String str, Class<T> clazz) {
            if (str == null || str.length() <= 0 || clazz == null) {
                return null;
            }
            if (clazz == int.class || clazz == Integer.class) {
                return (T) Integer.valueOf(str);
            } else if (clazz == String.class) {
                return (T) str;
            } else if (clazz == long.class || clazz == Long.class) {
                return (T) Long.valueOf(str);
            } else {
                return JSON.toJavaObject(JSON.parseObject(str), clazz);
            }
        }

        /**
         * 将其他对象转换为String
         * @param value
         * @param <T>
         * @return
         */
        private <T> String beanToString(T value) {
            if (value == null) {
                return null;
            }
            Class<?> clazz = value.getClass();
            if (clazz == int.class || clazz == Integer.class) {
                return "" + value;
            } else if (clazz == String.class) {
                return (String) value;
            } else if (clazz == long.class || clazz == Long.class) {
                return "" + value;
            } else {
                return JSON.toJSONString(value);
            }
        }
    }

Jedis测试类

package com.springboot.redis.Jedis;/**
 * @author Mr伍
 * @date 2020/9/11 17:49
 */

import com.alibaba.fastjson.JSONObject;
import com.springboot.redis.common.service.impl.JedisServiceImpl;
import com.springboot.redis.model.Swagger2;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import redis.clients.jedis.JedisPool;

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

/**
 * Created with IntelliJ IDEA.
 * @ClassName: JedisSetGetTest
 * @Auther: Mr伍
 * @Date: 2020/09/11/17:49
 */


@RunWith(SpringRunner.class)
@SpringBootTest
public class JedisSetGetTest {

    @Autowired
    private JedisServiceImpl jedisService;

    @Test
    public  void  JedisSet(){
        ArrayList<Swagger2> list=new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            Swagger2 swagger2 =new Swagger2();
            swagger2.setAge(20+i);
            swagger2.setName("Jedis"+i);
            swagger2.setId(i+"");
            list.add(swagger2);

        }
        boolean b = jedisService.set("swagger2",new Swagger2() );
        if(b){
            System.err.println("数据缓存成功");
        }else {
            System.err.println("缓存失败");
        }


    }

    @Autowired
    JedisPool jedisPool;
    @Test
    public void getJedisValue(){

     String getJedis= jedisService.get("jedis",String.class);
        List<Swagger2> list = JSONObject.parseArray(getJedis,Swagger2.class);
        System.err.println(list);

       Swagger2 s=jedisService.get("swagger2",Swagger2.class);

        System.err.println(s);

        }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值