springboot中redis怎么使用


在Spring Boot中使用Redis,可以使用以下步骤:
1. 添加依赖:在`pom.xml`文件中添加Redis的依赖:
```xml

org.springframework.boot
spring-boot-starter-data-redis

```
2. 配置Redis连接:在`application.properties`中配置Redis连接信息,例如:
```
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
```
3. 创建Redis配置类:创建一个Redis配置类,用于配置Redis连接池和RedisTemplate等,例如:
```java
@Configuration
@EnableCaching
public class RedisConfig {
@Bean
public JedisConnectionFactory jedisConnectionFactory() {
RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
configuration.setHostName("localhost");
configuration.setPort(6379);
return new JedisConnectionFactory(configuration);
}
@Bean
public RedisTemplate redisTemplate() {
RedisTemplate template = new RedisTemplate();
template.setConnectionFactory(jedisConnectionFactory());
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return template;
}
}
```
4. 使用RedisTemplate操作Redis:在需要使用Redis的地方注入`RedisTemplate`,并使用其方法操作Redis,例如:
```java
@Autowired
private RedisTemplate redisTemplate;
public void setValue(String key, Object value) {
redisTemplate.opsForValue().set(key, value);
}
public Object getValue(String key) {
return redisTemplate.opsForValue().get(key);
}
```
这样就可以在Spring Boot中使用Redis了。通过`RedisTemplate`可以使用各种操作Redis的方法,如`opsForValue()`用于操作字符串类型的数据,`opsForHash()`用于操作哈希类型的数据等。


上一篇:如何把数据放到redis

下一篇:多线程测试redis连接的方法是什么


Copyright © 2002-2019 测速网 www.inhv.cn 皖ICP备2023010105号
测速城市 测速地区 测速街道 网速测试城市 网速测试地区 网速测试街道
温馨提示:部分文章图片数据来源与网络,仅供参考!版权归原作者所有,如有侵权请联系删除!

热门搜索 城市网站建设 地区网站制作 街道网页设计 大写数字 热点城市 热点地区 热点街道 热点时间 房贷计算器