Springboot集成redis示例(一)

1. 添加依赖

pom.xml中添加必要的依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>

2. 配置Redis

application.propertiesapplication.yml中配置Redis:

spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=yourpassword

3. 创建Redis配置类

创建一个Redis配置类,用于配置RedisTemplate

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
​
@Configuration
public class RedisConfig {
​
    @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进行交互:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    private final RedisTemplate<String, Object> redisTemplate;

    @Autowired
    public UserService(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public void saveUser(String userId, User user) {
        //保存到数据库中
        userDao.save(user);
    }

    public User getUser(String userId) {
        User user = (User) redisTemplate.opsForValue().get("USER_" + userId);
        if(user != null)
            return user;
        User user = userDao.getById(userId);
        redisTemplate.opsForValue().set("USER_" + userId, user);
        // 设置过期时间(可选)
        redisTemplate.expire("USER_" + userId, 10, TimeUnit.MINUTES);
        return user;
    }

    public void deleteUser(String userId) {
        redisTemplate.delete("USER_" + userId);
    }
}

5. 创建用户实体类

创建一个简单的用户实体类:

import java.io.Serializable;
​
public class User implements Serializable {
    private Long id;
    private String name;
    private int age;
​
    // Getters and Setters
​
    public Long getId() {
        return id;
    }
​
    public void setId(Long id) {
        this.id = id;
    }
​
    public String getName() {
        return name;
    }
​
    public void setName(String name) {
        this.name = name;
    }
​
    public int getAge() {
        return age;
    }
​
    public void setAge(int age) {
        this.age = age;
    }
}

6. 使用服务类

在你的控制器或其他服务类中使用UserService

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
​
@RestController
@RequestMapping("/users")
public class UserController {
​
    private final UserService userService;
​
    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }
​
    @PostMapping
    public void createUser(@RequestBody User user) {
        userService.saveUser(user.getId().toString(), user);
    }
​
    @GetMapping("/{id}")
    public User getUser(@PathVariable String id) {
        return userService.getUser(id);
    }
​
    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable String id) {
        userService.deleteUser(id);
    }
}

总结

通过上述步骤,你可以在Spring Boot项目中集成Redis进行数据查询和存储,而不依赖缓存机制。这样可以利用Redis的高性能特性,提高数据存取速度,特别适合需要快速读取和写入的数据场景。

Springboot集成redis缓存示例(二)-CSDN博客

  • 22
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot项目中,有三种方式可以集成Redis集群,包括使用Jedis、Lettuce和RedisTemplate。 对于Jedis的整合步骤,你需要先导入相应的依赖,包括spring-boot-starter-data-redis和lettuce-core。然后,你可以通过配置类来修改Swagger配置,以便适应你的项目需求。具体的代码实现可以参考上面给出的示例。 对于Lettuce的整合步骤,你同样需要导入相应的依赖,包括spring-boot-starter-data-redis和lettuce-core。然后,你可以在配置类中根据需要修改Swagger配置。具体的代码实现可以参考上面给出的示例。 对于RedisTemplate的整合步骤,你同样需要导入相应的依赖,包括spring-boot-starter-data-redis和lettuce-core。然后,你可以在配置类中根据需要修改Swagger配置。具体的代码实现可以参考上面给出的示例。 总结来说,不论是使用Jedis、Lettuce还是RedisTemplate,你都需要导入相应的依赖并进行相应的配置,以便在Spring Boot项目中实现Redis集群的整合。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [springboot整合redis集群](https://blog.csdn.net/m0_68574821/article/details/129899360)[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: 50%"] - *2* [SpringBoot整合Redis](https://blog.csdn.net/l_zl2021/article/details/129368515)[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: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值