1、添加项目依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
2、单实例连接
//Jedis单机测试
@Test
public void testJedisSingle() {
Jedis jedis = new Jedis("127.0.0.1", 6379);
jedis.set("str", "单机测试Jedis");
String str = jedis.get("str");
System.out.println(str);
jedis.close();
}
3、使用连接池连接
//Jedis连接池测试
@Test
public void testJedisPool() {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
//最大连接数
jedisPoolConfig.setMaxTotal(30);
//最大连接空闲数
jedisPoolConfig.setMaxIdle(2);
JedisPool jedisPool = new JedisPool(jedisPoolConfig, "127.0.0.1", 6379);
Jedis resourceJedis = jedisPool.getResource();
resourceJedis.set("str", "Jedis连接池测试");
String str = resourceJedis.get("str");
System.out.println(str);
resourceJedis.close();
}
4、编写JedisConfig 配置
package com.yy.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
@Configuration
public class JedisConfig {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.jedis.pool.max-active}")
private int maxActive;
@Value("${spring.redis.jedis.pool.max-idle}")
private int maxIdle;
@Value("${spring.redis.jedis.pool.min-idle}")
private int minIdle;
@Bean
public JedisPoolConfig jedisPoolConfig() {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxIdle(maxIdle);
jedisPoolConfig.setMinIdle(minIdle);
jedisPoolConfig.setMaxTotal(maxActive);;
return jedisPoolConfig;
}
@Bean
public JedisPool jedisPool(JedisPoolConfig jedisPoolConfig){
return new JedisPool(jedisPoolConfig,host,port);
}
}
5、application.yml 配置文件文章来源:https://www.toymoban.com/news/detail-820010.html
spring:
redis:
host: localhost
port: 6379
jedis:
pool:
max-idle: 6 #最大空闲数
max-active: 10 #最大连接数
min-idle: 2 #最小空闲数
文章来源地址https://www.toymoban.com/news/detail-820010.html
到了这里,关于SpringBoot 整合redis的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!