首页 > 数据库 >Spring Boot 操作 Redis

Spring Boot 操作 Redis

时间:2022-09-20 17:01:06浏览次数:120  
标签:Boot Spring boot redis springframework key import org Redis

目录

参考资料

说在前面

Spring Boot 项目提供 LettuceJedis 客户端基本的自动配置;Spring Data Redis 项目提供了 Lettuce 和 Jedis 上层的抽象。

默认使用 Lettuce 客户端。

步骤

1. 新建 Maven 项目并引入 spring-boot-starter-data-redis

        <!-- 引入 spring-boot-starter-data-redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>2.3.12.RELEASE</version>
        </dependency>
        <!-- spring boot 的 lettuce 连接池依赖 commons-pool2 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.8.1</version>
        </dependency>
        <!-- 引入 spring-boot-starter-web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.3.12.RELEASE</version>
        </dependency>

2. 编写 application.yml

编写 yml 的方式是安装插件,我这里使用的idea插件是 Spring Boot Assistant

# 应用端口
server:
  port: 8090

spring:
  application:
    name: spring-boot-redis-demo #应用名
  redis:
    #url: "redis://user:[email protected]:6379" # 此配置可覆盖 host,post,password 配置
    database: 255                  # redis 数据库下标
    host: {主机地址}            # redis 数据库主机地址
    port: 6379                   # redis 数据库端口
    password: {密码}                 # redis 数据库密码(没有密码可不配置)
    timeout: 6000                # 获取连接超时时间
    ssl: false                   # 是否开启 SSL 支持
    lettuce:                     # lettuce 是基于 Netty 实现的 redis 客户端,spring boot 默认使用此客户端
      pool:
        max-active: 8            # 规定时间内连接池能够分配的连接的最大数量
        max-idle: 8              # 连接池中允许空闲连接的最大数量
        min-idle: 0              # 连接池中允许空闲连接的最小数量
        max-wait: -1ms           #连接分配最大等待时间,负数表示一直等待分配连接
        #time-between-eviction-runs: # 回收空闲连接线程执行时间间隔
    #cluster:                       # redis cluster配置。
      #  max-redirects: 100             # 跨集群执行命令时要遵循的最大重定向数。
      #  nodes:                      # Redis集群服务列表(可配置多个)
      #    - "host:port"
    #sentinel:                      #  redis 哨兵配置
      #  master:                    #  redis 服务器名字
      #  password:                  #  redis 哨兵密码
      #  nodes:                     #  redis 哨兵各节点(可配置多个)
      #       -

3. 编写缓存服务和Controller

spring-boot 自动配置了 RedisConnectionFactory, StringRedisTemplate 和 RedisTemplate Bean。
默认,连接的 redis 服务端为 localhost:6379

CacheService 接口(点击查看代码)
/**
 * 缓存服务
 * @param <K>  缓存的 key
 * @param <V>  缓存的内容
 */
public interface CacheService<K,V> {

    Boolean cache(K key, V value);

    Boolean remove(K key);

    V get(K key);

}


RedisCacheService(点击查看代码)
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * 基于 Redis 实现的的缓存服务
 */
@Service("redisCacheService")
public class RedisCacheService implements CacheService<String, Object>{

    //  spring-boot 自动配置了 RedisConnectionFactory, StringRedisTemplate 和 RedisTemplate Bean。
    @Autowired
    private RedisConnectionFactory connectionFactory;

    @Autowired
    private StringRedisTemplate template;

    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;

    @Override
    public Boolean cache(String key, Object value) {
        template.opsForValue().set(key,String.valueOf(value));
        return Boolean.TRUE;
    }

    @Override
    public Boolean remove(String key) {
        return template.delete(key);
    }

    @Override
    public Object get(String key) {
        return template.opsForValue().get(key);
    }
}
CacheController:(点击查看代码)
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * CacheController 用于提供 接口进行缓存操作
 */
@RestController
@RequestMapping("/cache")
public class CacheController {

    @Autowired
    @Qualifier("redisCacheService")
    private CacheService cacheService;

    /**
     * 缓存
     * @param key
     * @param value
     * @return
     */
    @GetMapping("/save")
    public Boolean cache(@RequestParam("key") String key, @RequestParam("value")String value){
        return cacheService.cache(key,value);
    }

    /**
     * 查询
     * @param key 缓存key
     * @return
     */
    @GetMapping("/get")
    public Object get(@RequestParam("key") String key){
        return cacheService.get(key);
    }

    /**
     * 删除缓存
     * @param key 缓存key
     * @return
     */
    @GetMapping("/remove")
    public Boolean remove(@RequestParam("key") String key){
        return cacheService.remove(key);
    }
}

4. 启动类


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * spring boot redis demo 启动类
 */
@SpringBootApplication
public class SpringBootRedisAppBootstrap {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootRedisAppBootstrap.class,args);
    }
}

5.测试

image

image

标签:Boot,Spring,boot,redis,springframework,key,import,org,Redis
From: https://www.cnblogs.com/lihw-study/p/16708694.html

相关文章

  • SpringMVC学习笔记(四)
    拦截器拦截器需要实现HandlerInterceptor接口然后配置到IOC文件中在mvc:interceptors标签中配置拦截器bean或ref这种方式会拦截所有路径在mvc:interceptors标签中配置......
  • Spring事务传播机制
    传播性行为分为以下几种PROPAGATION_REQUIRED--支持当前事务,如果当前没有事务,就新建一个事务。这是最常见的选择。PROPAGATION_SUPPORTS--支持当前事务,如果当前没有事务......
  • Spring事务隔离级别
    事务隔离级别ISOLATION_DEFAULT这是一个PlatfromTransactionManager默认的隔离级别,使用数据库默认的事务隔离级别。ISOLATION_READ_UNCOMMITTED这是事务最低的隔离级别......
  • redis distributed lock redis分布式锁试下
    @ResourceprivateDistributedRedisLockTemplatelockTemplate;StringdistributedKey="lockKey";DistributedLockCallback<String>callback=newDistributedLockCal......
  • JAVA入门基础_从零开始的培训_Redis
    目录Redis能够为我们解决什么问题Redis的下载与安装前台启动(不推荐)与后台启动常用五大数据类型Redis键常用命令(key)4个数据库操作命令String字符串命令String的内存结构Li......
  • 计算机毕业设计 SpringBoot 农机电招平台系统 农业设备管理系统 农业设备预约平台 Jav
    ......
  • SpringBoot 代理转发网关
    RestTemplate工具类:importorg.springframework.http.*;importorg.springframework.stereotype.Service;importorg.springframework.util.MultiValueMap;importorg......
  • 模拟springboot自动转配原理
    packagecom.tlj.app;importorg.springframework.beans.factory.annotation.Configurable;importorg.springframework.context.annotation.Bean;importorg.springf......
  • Spring-基于XML管理bean
    1.导入依赖pom.xml<dependencies><!--基于Maven依赖传递性,导入spring-context依赖即可导入当前所需所有jar包--><dependency><groupId>org.springframework</g......
  • spring boot 自定义 yml 配置需要用到的注解
    importlombok.Data;importorg.springframework.boot.context.properties.ConfigurationProperties;importorg.springframework.context.annotation.Configuration;......