1.首先引入依赖包
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
2.然后在工程中创建两个类RedisConfig和RedisUtil,RedisConfig负责在spring容器启动时自动注入,而RedisUtil就是被注入的类
2.1 RedisUtil
public class RedisUtil {
private JedisPool jedisPool;
public void initPool(String host,int port ,int database){
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(200);
poolConfig.setMaxIdle(30);
poolConfig.setBlockWhenExhausted(true);
poolConfig.setMaxWaitMillis(10*1000);
poolConfig.setTestOnBorrow(true);
jedisPool=new JedisPool(poolConfig,host,port,20*1000);
}
public Jedis getJedis(){
Jedis jedis = jedisPool.getResource();
return jedis;
}
}
2.2 RedisConfig
@Configuration
public class RedisConfig {
//读取配置文件中的redis的ip地址
@Value("${spring.redis.host:disabled}")
private String host;
@Value("${spring.redis.port:0}")
private int port;
@Value("${spring.redis.database:0}")
private int database;
@Bean
public RedisUtil getRedisUtil(){
if(host.equals("disabled")){
return null;
}
RedisUtil redisUtil=new RedisUtil();
redisUtil.initPool(host,port,database);
return redisUtil;
}
}
3.同时,任何工程模块想要调用redis都必须application.properties配置,否则不会进行注入。
spring.redis.host=redis.server.com
spring.redis.port=6379
spring.redis.database=0
4.到这就整合完了,在test包下进行测试
try {
Jedis jedis = redisUtil.getJedis();
System.out.println(jedis);
}catch (JedisConnectionException e){
e.printStackTrace();
}