SpringBoot 整合 Redis

SpringBoot 整合 Redis

1 引入redis

通过springboot初始化整合redis

在这里插入图片描述
在这里插入图片描述
其生成的pom.xml中会有

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
通过添加maven依赖
 <dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>2.9.0</version>
 </dependency>

2 配置连接信息

如果要远程连接服务器上的redis需要将redis.conf中的bind:127.0.0.1注释掉,并且将protected-mode yes修改为protected-mode no

# redis所在主机的ip
spring.redis.host=127.0.0.1
# redis所在主机配置的端口
spring.redis.port=6379
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=10
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.lettuce.shutdown-timeout=0
spring:
    redis:
      host: 127.0.0.1 
      port: 6379
      password: 123456
      jedis:
        pool:
          max-active: 8
          max-wait: -1
          max-idle: 500
          min-idle: 0
      lettuce:
        shutdown-timeout: 0

3 测试连接

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
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;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@RunWith(SpringRunner.class)
@SpringBootTest
class SpringredisApplicationTests {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * spring 初始化方法连接redis
     */
    @Test
    public void setRedisString() {
        redisTemplate.opsForValue().set("connection_test", "ok");
        System.out.println(redisTemplate.opsForValue().get("connection_test"));
    }

    /**
     * 手动导入maven依赖
     */
    @Test
    public void setRedisStringV2() {
        GenericObjectPoolConfig pool = new GenericObjectPoolConfig();
        JedisPool jedisPool = new JedisPool(pool, "127.0.0.1", 6379);

        Jedis jedis = null;
        try {
            // 从连接池获取jedis对象
            jedis = jedisPool.getResource();
            // 执行操作
            jedis.set("hello", "world");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                // 如果使用连接池的话 close操作代表归还连接池而不是关闭连接。
                jedis.close();
            }
        }

    }
}

4 测试结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值