springboot集成RedisTemplate

基本信息

spring 封装了 RedisTemplate 对象来进行对redis的各种操作,它支持所有的 redis 原生的 api。

操作系统:windows10

IDE:IDEA2019

project:spring-boot

Maven依赖

        <!--RedisTemplate 依赖-->
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>
		<!--spring-boot-web启动器-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--JSON 数据转换支持-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.0</version>
        </dependency>

yml配置文件

# 配置服务应用端口
server:
  port: 8080

spring:
  jmx:
    enabled: false
  redis:
    ## Redis数据库索引(默认为0)
    database: 0
    ## Redis服务器地址
    host: 127.0.0.1
    ## Redis服务器连接端口
    port: 6379
    ## Redis服务器连接密码(默认为空)
    password:

    database-osp: 0
    host-osp: 127.0.0.1
    port-osp: 6379
    password-osp:

    lettuce:
      pool:
        ## 连接池最大连接数(使用负值表示没有限制)
        max-active: 60
        ## 连接池最大阻塞等待时间(使用负值表示没有限制)
        max-wait: -1ms
        ## 连接池中的最大空闲连接
        max-idle: 20
        ## 连接池中的最小空闲连接
        min-idle: 8
    ## 连接超时时间(毫秒)
    timeout: 300000ms

rest:
  # restTemplate 超时配置
  connect-timeout: 60000
  read-timeout: 60000
  pool-connect-timeout: 60000





redisConfig配置类

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;


@Configuration
public class RedisConfig {

    @Bean
    @ConditionalOnMissingBean(name = "redisTemplate")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        //设置序列化
        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer<Object> jacksonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper om = new ObjectMapper();

        //指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonRedisSerializer.setObjectMapper(om);

        //配置redisTemplate
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 配置连接工厂
        template.setConnectionFactory(factory);

        //String类的序列化方式
        RedisSerializer stringSerializer = new StringRedisSerializer();
        template.setKeySerializer(stringSerializer);//key序列化
        template.setValueSerializer(jacksonRedisSerializer);//value序列化
        template.setHashKeySerializer(stringSerializer);//Hash key序列化
        template.setHashValueSerializer(jacksonRedisSerializer);//Hash value序列化
        template.afterPropertiesSet();
        return template;
    }

    @Bean
    @ConditionalOnMissingBean(StringRedisTemplate.class)
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(factory);
        return template;
    }
}

Redis操作string

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * explain: RedisTemplate操作string
 * public interface ValueOperations<K,V>
 * Redis operations for simple (or in Redis terminology 'string') values.
 * ValueOperations可以对String数据结构进行操作
 */

@RestController
@RequestMapping(value = "redisTemplate", produces = "application/json;charset=UTF-8")
public class RedisOperateString {

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    /**
     * RedisTemplate操作string
     */
    @GetMapping("/operateString")
    private String operateString() {
        ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
        //清空redis
        deleteAllKey();

        //void set(K key, V value);
        opsForValue.set("key1", "cat");
        System.out.println(opsForValue.get("key1"));

        //void set(K key, V value, long timeout, TimeUnit unit);
        //由于设置的是10秒失效,十秒之内查询有结果,十秒之后返回为null
        opsForValue.set("key2", "tom", 10, TimeUnit.SECONDS);
        Object key2 = opsForValue.get("key2");
        System.out.println(key2);

        // multiSet void multiSet(Map<? extends K, ? extends V> m);为多个键分别设置它们的值
        Map<String, String> maps = new HashMap<>();
        maps.put("multiKey1", "multi11");
        maps.put("multiKey2", "multi22");
        maps.put("multiKey3", "multi33");
        opsForValue.multiSet(maps);

        Set<String> keyList = maps.keySet();
        // List<String> keyList = new ArrayList<>(maps.keySet());
        List<Object> list = opsForValue.multiGet(keyList);
        System.out.println(list);

        // getAndSet V getAndSet(K key, V value); 设置键的字符串值并返回其旧值
        opsForValue.set("multiKey4", "multi44");
        System.out.println(opsForValue.getAndSet("multiKey4", "multi"));

        // multiSetIfAbsent Boolean multiSetIfAbsent(Map<? extends K, ? extends V> m);
        // 为多个键分别设置它们的值,如果存在则返回false,不存在返回true
        Boolean aBoolean = opsForValue.multiSetIfAbsent(maps);
        System.out.println(aBoolean);

        // multiGet List<V> multiGet(Collection<K> keys);为多个键分别取出它们的值
        ArrayList<String> keyLists = new ArrayList<>();
        keyLists.add("key1");
        keyLists.add("key2");
        keyLists.add("multiKey1");
        keyLists.add("multiKey2");
        keyLists.add("multiKey3");
        keyLists.add("multiKey4");

        List<Object> objects = opsForValue.multiGet(keyLists);
        System.out.println(objects);

        // increment Long increment(K key, long delta);支持整数
        Long longKey = opsForValue.increment("longKey", 99);
        System.out.println(longKey);
        System.out.println(opsForValue.get("longKey"));

        // increment Double increment(K key, double delta);也支持浮点数
        Double doubleKey = opsForValue.increment("doubleKey", 99.99);
        System.out.println(doubleKey);
        System.out.println(opsForValue.get("doubleKey"));

        // append Integer append(K key, String value);
        // 如果key已经存在并且是一个字符串,则该命令将该值追加到字符串的末尾。
        // 如果键不存在,则它被创建并设置为空字符串,因此APPEND在这种特殊情况下将类似于SET。
        // append()这里redisConfig使用jacksonRedisSerializer序列化方式时会出现序列化失败的情况,导致无法获取value
        opsForValue.append("appendKye", "hello");
        opsForValue.append("appendKye", "world ");
        Object appendKye = opsForValue.get("appendKye");
        System.out.println(appendKye);

        // get String get(K key, long start, long end);截取key所对应的value字符串
        opsForValue.set("key4", "HelloWorld");
        System.out.println(opsForValue.get("key4", 0, 4));
        System.out.println(opsForValue.get("key4", 0, -1));
        System.out.println(opsForValue.get("key4", 0, -6));

        // size Long size(K key); 返回key所对应的value值得长度
        Long key4 = opsForValue.size("key4");
        System.out.println(key4);

        return "method completed ok";
    }


    /**
     * 删除redis中所有的key
     */
    private void deleteAllKey() {
        //获取所有key
        Set<String> keys = redisTemplate.keys("*");
        System.out.println(keys);
        Long delete = redisTemplate.delete(keys);
        System.out.println(delete);
    }
}


Redis操作list


/**
 * explain:public interface ListOperations<K,V>
 * Redis列表是简单的字符串列表,按照插入顺序排序。你可以添加一个元素导列表的头部(左边)或者尾部(右边)
 * ListOperations专门操作list列表
 */

@RestController
@RequestMapping(value = "redisList", produces = "application/json;charset=UTF-8")
public class RedisOperateList {

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    /**
     * RedisTemplate操作list
     */
    @GetMapping("/operateList")
    private String operateList() {
        ListOperations<String, Object> opsForList = redisTemplate.opsForList();
        deleteAllKey();

        // Long leftPush(K key, V value);
        // 将所有指定的值插入存储在键的列表的头部。如果键不存在,则在执行推送操作之前将其创建为空列表。(从左边插入)
        opsForList.leftPush("product:list", "iphone xs max");
        opsForList.leftPush("product:list", "thinkpad x1 carbon");


        // List<V> range(K key, long start, long end);
        // 返回存储在键中的列表的指定元素。偏移开始和停止是基于零的索引,其中0是列表的第一个元素(列表的头部),1是下一个元素
        List<Object> opsList = opsForList.range("product:list", 0, -1);
        System.out.println(opsList);


        // Long leftPushAll(K key, V... values);批量把一个数组插入到列表中
        Object[] stringArr = new String[]{"1", "2", "3"};
        opsForList.leftPushAll("product:list", stringArr);
        System.out.println(opsForList.range("product:list", 0, -1));

        // Long size(K key);
        // 返回存储在键中的列表的长度。如果键不存在,则将其解释为空列表,并返回0。当key存储的值不是列表时返回错误。
        Long size = opsForList.size("product:list");
        System.out.println(size);

        //Long leftPushAll(K key, Collection<V> values);批量把一个集合插入到列表中
        ArrayList<Object> list = new ArrayList<>();
        list.add("4");
        list.add("5");
        list.add("6");
        opsForList.leftPushAll("product:list1", list);
        System.out.println(opsForList.range("product:list1", 0, -1));

        //Long leftPushIfPresent(K key, V value);只有存在key对应的列表才能将这个value值插入到key所对应的列表中
        opsForList.leftPushIfPresent("product:list1", "7");
        System.out.println(opsForList.range("product:list1", 0, -1));


        // Long leftPush(K key, V pivot, V value);把value值放到key对应列表中pivot值的左面,(如果pivot值存在的话)
        opsForList.leftPush("product:list1", "4", "8");
        System.out.println(opsForList.range("product:list1", 0, -1));

        // Long rightPush(K key, V value);
        // 将所有指定的值插入存储在键的列表的头部。如果键不存在,则在执行推送操作之前将其创建为空列表。(从右边插入)
        opsForList.rightPush("product:list1", "java");

        // Long rightPushAll(K key, V... values);
        opsForList.rightPushAll("product:list1", stringArr);
        opsForList.rightPushAll("product:list1", list);
        System.out.println(opsForList.range("product:list1", 0, -1));

        // Long rightPushIfPresent(K key, V value);
        // 只有存在key对应的列表才能将这个value值插入到key所对应的列表中
        opsForList.rightPushIfPresent("product:list1", "7");
        System.out.println(opsForList.range("product:list1", 0, -1));

        // Long rightPush(K key, V pivot, V value);
        // 把value值放到key对应列表中pivot值的右面,如果pivot值存在的话
        opsForList.rightPush("product:list1", "8");
        System.out.println(opsForList.range("product:list1", 0, -1));

        // void set(K key, long index, V value);在列表中index的位置设置value值
        opsForList.set("product:list1", 5, "java1");
        System.out.println(opsForList.range("product:list1", 0, 7));

        // Long remove(K key, long count, Object value);
        // 从存储在键中的列表中删除等于值的元素的第一个计数事件。
        // 计数参数以下列方式影响操作:
        // count> 0:删除等于从头到尾移动的值的元素。
        // count <0:删除等于从尾到头移动的值的元素。
        // count = 0:删除等于value的所有元素。
        opsForList.remove("product:list1", 0, "java1");
        System.out.println(opsForList.range("product:list1", 0, -1));

        // V index(K key, long index);根据下表获取列表中的值,下标是从0开始的
        Object index = opsForList.index("product:list1", 0);
        System.out.println(index);

        // V leftPop(K key);弹出最左边的元素,弹出之后该值在列表中将不复存在
        Object leftPop = opsForList.leftPop("product:list1");
        System.out.println(leftPop);

        // V leftPop(K key, long timeout, TimeUnit unit);
        // 移出并获取列表的第一个元素, 如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止。
        opsForList.leftPop("product:list1", 10, TimeUnit.SECONDS);

        // V rightPop(K key);弹出最右边的元素,弹出之后该值在列表中将不复存在
        System.out.println(opsForList.rightPop("product:list1"));

        // V rightPopAndLeftPush(K sourceKey, K destinationKey);
        // 用于移除列表的最后一个元素,并将该元素添加到另一个列表并返回。
        opsForList.rightPopAndLeftPush("product:list1", "product:list2");
        // V rightPopAndLeftPush(K sourceKey, K destinationKey, long timeout, TimeUnit unit);
        // 用于移除列表的最后一个元素,并将该元素添加到另一个列表并返回,如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止。
        // 使用:用法与rightPopAndLeftPush(K sourceKey, K destinationKey)一样
        
        return "method completed ok";
    }

    /**
     * 删除redis中所有的key
     */
    private void deleteAllKey() {
        //获取所有key
        Set<String> keys = redisTemplate.keys("*");
        System.out.println(keys);
        Long delete = redisTemplate.delete(keys);
        System.out.println(delete);
    }
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

香辣奥利奥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值