不安分的黑娃
踏踏实实,坚持学习,慢慢就懂了~

参考资料

说在前面

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:password@example.com: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

posted on 2022-09-20 16:54  不安分的黑娃  阅读(594)  评论(0编辑  收藏  举报