一、首先安装redis,下面教程
二、导入操作redis的库jedis
pom文件中加入依赖
text
1
2
3
4
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
三、写一个redis的配置类,并加上@Configuration的注解,表示加入到ioc容器当中
redis的配置类
text
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@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;
@Value("${spring.redis.password:0}")
private String password;
@Bean
public RedisUtil getRedisUtil(){
if(host.equals("disabled")){
return null;
}
RedisUtil redisUtil=new RedisUtil();
redisUtil.initPool(host,port,database,password);
return redisUtil;
}
}
redis的连接实现
text
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class RedisUtil {
private JedisPool jedisPool;
public void initPool(String host,int port ,int database,String password){
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,password);
}
public Jedis getJedis(){
Jedis jedis = jedisPool.getResource();
return jedis;
}
}
redis的配置文件
text
1
2
3
4
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.database=0
spring.redis.password=root #你的redis密码,没有密码则不写
四、测试是否连接成功!
text
1
2
3
4
5
6
7
8
@Autowired
RedisUtil redisUtil;
public void test(){
// 查询缓存
jedis = redisUtil.getJedis();
String skuJSON = jedis.get("a");
System.out.println(skuJSON);
}
没有报错,并输出了和你redis中一样的数据,说明成功!