springboot整合redis

Posted 阿拉的梦想

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot整合redis相关的知识,希望对你有一定的参考价值。

依赖管理pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>springboot-redis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-redis</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

配置管理application.properties

可以配置单机redis,也可以配置redis cluster集群

server.port=8002
# Redis数据库索引(默认为0)
spring.redis.database=8
# Redis服务器地址
spring.redis.host=10.128.162.142
#spring.redis.cluster.nodes=127.0.0.1:7000,127.0.0.1:7001,127.0.0.1:7002,127.0.0.1:7003,127.0.0.1:7004,127.0.0.1:7005
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
#spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=30

# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=200
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=5000
# 看门狗时间,到时还没释放则延长
spring.redis.lock-watchdog-timeout=1000

常用接口示例

列举了常用数据类型的保存和查询方法

package com.example.springbootredis.controller;

import com.example.springbootredis.RedisUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * redis测试
 */
@Slf4j
@RestController
public class TestController {
    final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 用@Autoweired不带泛型的注入,或者用@Resource带泛型的注入
     */
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 1.保存和读取String
     * @return
     */
   @GetMapping("saveString")
   public String saveString(){
       //保存string到redis,1天后过期
       stringRedisTemplate.opsForValue().set("name","tom",1,TimeUnit.DAYS);
       //读取string 
       final String name = this.stringRedisTemplate.opsForValue().get("name");
       log.info("name={}",name);
       return name;
   }
    /**
     * 2.保存和读取Set
     *
     * @param request
     * @return
     */
    @GetMapping("saveSet")
    public String saveSet(HttpServletRequest request) {

        SetOperations<String, String> set = redisTemplate.opsForSet();
        set.add("set1", "22");
        set.add("set1", "33");
        set.add("set1", "44");
        Set<String> resultSet = redisTemplate.opsForSet().members("set1");
        System.out.println("resultSet:" + resultSet);
        return "success";
    }

    /**
     * 3.保存和读取map:
     */
    @GetMapping("saveMap")
    public String saveMap(HttpServletRequest request) {
        Map<String, String> map = new HashMap<String, String>();

        map.put("key1", "value1");
        map.put("key2", "value2");
        map.put("key3", "value3");
        map.put("key4", "value4");
        map.put("key5", "value5");

        redisTemplate.opsForHash().putAll("map1", map);
        Map<Object, Object> resultMap = redisTemplate.opsForHash().entries("map1");
        System.out.println("resultMap:" + resultMap);
        List<Object> reslutMapList = redisTemplate.opsForHash().values("map1");
        System.out.println("resulreslutMapListtMap:" + reslutMapList);
        Set<Object> resultMapSet = redisTemplate.opsForHash().keys("map1");
        System.out.println("resultMapSet:" + resultMapSet);
        String value = (String) redisTemplate.opsForHash().get("map1", "key1");
        System.out.println("value:" + value);
        return "success";
    }

    /**
     * 4.保存和读取list
     */
    @GetMapping("saveList")
    public String saveList(HttpServletRequest request) {
        List<String> list1 = new ArrayList<String>();
        list1.add("a1");
        list1.add("a2");
        list1.add("a3");
        List<String> list2 = new ArrayList<String>();
        list2.add("b1");
        list2.add("b2");
        list2.add("b3");
        redisTemplate.opsForList().leftPush("listkey1", list1);
        redisTemplate.opsForList().rightPush("listkey2", list2);
        List<String> resultList1 = (List<String>) redisTemplate.opsForList().leftPop("listkey1");
        List<String> resultList2 = (List<String>) redisTemplate.opsForList().rightPop("listkey2");
        System.out.println("resultList1:" + resultList1);
        System.out.println("resultList2:" + resultList2);
        return "success";
    }

    /**
     * 5.保存和读取list
     */
    @GetMapping("saveObject")
    public String saveObject() {
        List<User> users = new ArrayList<>();
        final User tom = new User("tom", "124", 11);
        final User bob = new User("bob", "124", 11);
        final User jack = new User("jack", "124", 11);
        users.add(tom);
        users.add(bob);
        users.add(jack);
        redisTemplate.opsForList().leftPushAll("users", users);
        final List<User> users1 = redisTemplate.opsForList().range("users", 0, 10);
        System.out.println(users1);
        return "success";
    }

}

其他高级用法

springboot-redis管道pipline批量新增删除以及scan扫描
springboot-redis-redisson-bloomfilter布隆过滤器
springboot-redis-redisson分布式锁

以上是关于springboot整合redis的主要内容,如果未能解决你的问题,请参考以下文章

springboot整合mybatis,redis,代码

springboot整合mybatis,redis,代码

Shiro整合Springboot缓存之Redis实现

3分钟搞定springboot整合redis

springboot整合mybatis,redis,代码

完美取代hashmap,SpringBoot整合Redis缓存DB数据