spring boot配置连接redis样例

spring boot配置连接redis样例

一、安装redis
redis使用分为redis单机版、redis主从模式、redis哨兵模式和redis集群模式,本样例为redis单机版
redis下载地址为

https://github.com/microsoftarchive/redis/releases
在这里插入图片描述
放入redis文件夹中,解压到redis7000文件夹下
二、配置与启动
修改redis.windows.conf文件

port 7000

其他配置可以不用考虑
新建文本文档start.txt,其中添加以下语句
redis-server.exe redis.windows.conf
将start.txt改为start.bat作为启动文件
三、spring boot程序代码
1.通过maven引入jar包

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2.配置application.properties参数

#reids
spring.redis.database= 0
spring.redis.host= 127.0.0.1
spring.redis.port= 7029
spring.redis.password=
spring.redis.jedis.pool.max-active= 2000
spring.redis.jedis.pool.max-idle= 100
spring.redis.jedis.pool.min-idle= 50

3.添加RedisTemplate配置类

import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.io.Serializable;

@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisConfig {
@Bean
    public RedisTemplate<String, Serializable> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory){
        RedisTemplate<String, Serializable> template = new RedisTemplate<>();
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}

4.新建测试类

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;

@SpringBootTest
public class myredistest {
    @Autowired
    private RedisTemplate redisTemplate;
    @Test
    public void mytest(){
        redisTemplate.opsForValue().set("happy","开心");
        Object result = redisTemplate.opsForValue().get("happy");
        System.out.println(result);
    }
}

运行结果
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

未来悦,事享成

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

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

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

打赏作者

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

抵扣说明:

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

余额充值