springboot整合redis
时间: 2023-08-28 15:08:06 浏览: 86
Spring Boot整合Redis可以通过以下步骤进行:
1. 添加Redis的依赖
在pom.xml文件中添加以下依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
```
2. 配置Redis
在application.properties文件中添加以下配置:
```
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
```
3. 编写Redis配置类
创建RedisConfig类,配置Redis连接工厂、RedisTemplate、StringRedisTemplate等,代码如下:
```
@Configuration
public class RedisConfig {
@Bean
JedisConnectionFactory jedisConnectionFactory() {
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration("localhost", 6379);
JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(redisStandaloneConfiguration);
return jedisConnectionFactory;
}
@Bean
RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(jedisConnectionFactory());
return redisTemplate;
}
@Bean
StringRedisTemplate stringRedisTemplate() {
StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
stringRedisTemplate.setConnectionFactory(jedisConnectionFactory());
return stringRedisTemplate;
}
}
```
4. 测试Redis
在Controller中注入StringRedisTemplate,使用它进行Redis操作,代码如下:
```
@RestController
public class RedisController {
@Autowired
StringRedisTemplate stringRedisTemplate;
@GetMapping("/redis/set")
public String setRedis(String key, String value) {
stringRedisTemplate.opsForValue().set(key, value);
return "success";
}
@GetMapping("/redis/get")
public String getRedis(String key) {
String value = stringRedisTemplate.opsForValue().get(key);
return value;
}
}
```
通过上述步骤,就可以完成Spring Boot整合Redis的操作。
阅读全文