springboot集成 Redis快速入门demo

一、准备redis环境

这里用docker-compose来搭建Redis测试环境,采用单机模式,具体配置如下:

docker-compose-redis.yml

version: '3'
services:
  redis:
    image: registry.cn-hangzhou.aliyuncs.com/zhengqing/redis:6.0.8                    # image 'redis:6.0.8'
    container_name: redis                                                             # 容器名为'redis'
    restart: unless-stopped                                                                   # 指定容器退出后的重启策略为始终重启,但是不考虑在Docker守护进程启动时就已经停止了的容器
    command: redis-server /etc/redis/redis.conf --requirepass 123456 --appendonly no # 启动redis服务并添加密码为:123456,默认不开启redis-aof方式持久化配置
#    command: redis-server --requirepass 123456 --appendonly yes # 启动redis服务并添加密码为:123456,并开启redis持久化配置
    environment:                        # 设置环境变量,相当于docker run命令中的-e
      TZ: Asia/Shanghai
      LANG: en_US.UTF-8
    volumes:                            # 数据卷挂载路径设置,将本机目录映射到容器目录
      - "./redis/data:/data"
      - "./redis/config/redis.conf:/etc/redis/redis.conf"  # `redis.conf`文件内容`http://download.redis.io/redis-stable/redis.conf`
    ports:                              # 映射端口
      - "6379:6379"

二、搭建测试工程

1.pom.xml

<!--redis client-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
    <version>2.9.0</version>
</dependency>

2.RedisConfig.java

package com.et59.redis.config;


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.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;


/**
 * redisTemplate  config
 */
@Configuration
public class RedisConfig {


    /**
     * redis template.
     *
     * @param factory factory
     * @return RedisTemplate
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }
}

3.application.yaml

server:
  port: 8088
spring:
  redis:
    database: 0
    host: 127.0.0.1
    port: 6379
    password: 123456
    lettuce:
      pool:
        min-idle: 0
        max-active: 8
        max-idle: 8
        max-wait: -1ms
    connect-timeout: 30000ms

4.验证服务是否可用

package com.et.redis;
import com.et59.redis.DemoApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;




@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApplication.class)
public class RedisTests {
    private Logger log = LoggerFactory.getLogger(getClass());


    @Autowired
    private RedisTemplate redisTemplate;


    @Test
    public void save() {
        redisTemplate.opsForValue().set("test","this is a test");
        System.out.println(redisTemplate.opsForValue().get("test"));
    }




}

结果预期一样输出

. ____ _ __ _ _
 /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/ ___)| |_)| | | | | || (_| | ) ) ) )
 ' |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot :: (v2.2.5.RELEASE)


2024-01-25 17:10:48.566 INFO 18120 --- [ main] com.et.redis.RedisTests : Starting RedisTests on BJDPLHHUAPC with PID 18120 (started by Dell in D:\IdeaProjects\ETFramework\redis)
2024-01-25 17:10:48.567 INFO 18120 --- [ main] com.et.redis.RedisTests : No active profile set, falling back to default profiles: default
2024-01-25 17:10:49.143 INFO 18120 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2024-01-25 17:10:49.147 INFO 18120 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data Redis repositories in DEFAULT mode.
2024-01-25 17:10:49.178 INFO 18120 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 13ms. Found 0 Redis repository interfaces.
2024-01-25 17:10:50.165 INFO 18120 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2024-01-25 17:10:50.500 INFO 18120 --- [ main] com.et.redis.RedisTests : Started RedisTests in 2.222 seconds (JVM running for 2.901)
2024-01-25 17:10:50.785 INFO 18120 --- [ main] io.lettuce.core.EpollProvider : Starting without optional epoll library
2024-01-25 17:10:50.787 INFO 18120 --- [ main] io.lettuce.core.KqueueProvider : Starting without optional kqueue library
this is a test
2024-01-25 17:10:51.312 INFO 18120 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'

三、参考

  • https://docs.spring.io/spring-data/redis/reference/index.html

测试demo详见:https://github.com/Harries/springboot-demo

4c8ef11318b6123b1117f7d30e2e596e.jpeg

相关推荐

  1. Springboot集成hanlp快速入门demo

    2024-01-28 16:50:01       42 阅读
  2. spring boot集成flyway快速入门demo

    2024-01-28 16:50:01       36 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-28 16:50:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-28 16:50:01       100 阅读
  3. 在Django里面运行非项目文件

    2024-01-28 16:50:01       82 阅读
  4. Python语言-面向对象

    2024-01-28 16:50:01       91 阅读

热门阅读

  1. 【Vue】1-4、打包发布

    2024-01-28 16:50:01       60 阅读
  2. vue子组件调用父组件的方法

    2024-01-28 16:50:01       51 阅读
  3. 车载网络诊断测试攻略-专栏介绍

    2024-01-28 16:50:01       51 阅读
  4. PostgreSQL的full_page_writes

    2024-01-28 16:50:01       60 阅读
  5. Liunx运维批量启动、停止服务

    2024-01-28 16:50:01       65 阅读
  6. postgresql 12 安装

    2024-01-28 16:50:01       57 阅读