springboot3接入redis
时间: 2023-10-17 14:33:57 浏览: 33
要在Spring Boot中接入Redis,你可以按照以下步骤操作:
1. 在pom.xml文件中添加Redis依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
```
2. 在application.properties或application.yml文件中配置Redis连接信息:
```
spring.redis.host=127.0.0.1
spring.redis.port=6379
```
3. 创建一个Redis配置类,用于配置Redis连接池和RedisTemplate:
```java
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Bean
public RedisConnectionFactory redisConnectionFactory() {
RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(host, port);
return new JedisConnectionFactory(config);
}
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return template;
}
}
```
4. 在需要使用Redis的地方,使用@Autowired注解将RedisTemplate注入进来,然后就可以使用RedisTemplate操作Redis了。
```java
@Service
public class UserService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public User getUser(String id) {
String key = "user:" + id;
User user = (User) redisTemplate.opsForValue().get(key);
if (user == null) {
// 从数据库中获取用户信息
user = userRepository.findById(id);
// 将用户信息存入Redis中
redisTemplate.opsForValue().set(key, user);
}
return user;
}
}
```
通过以上步骤,你可以在Spring Boot应用中成功接入Redis,并使用RedisTemplate进行数据操作。<span class="em">1</span>
#### 引用[.reference_title]
- *1* [springboot接入cachecloud redis示例实践](https://download.csdn.net/download/weixin_38672739/12745727)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]