springboot中怎么使用redis

fiy 其他 20

回复

共3条回复 我来回复
  • 不及物动词的头像
    不及物动词
    这个人很懒,什么都没有留下~
    评论

    在Spring Boot中使用Redis可以通过以下步骤:

    1. 添加Redis依赖:在pom.xml文件中添加以下依赖关系:
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    
    1. 配置Redis连接:在application.properties或application.yml文件中添加以下配置信息:
    spring.redis.host=your-redis-host
    spring.redis.port=your-redis-port
    spring.redis.password=your-redis-password
    

    你需要根据你的实际情况替换好每个属性的值。

    1. 创建RedisTemplate Bean:在配置类中创建RedisTemplate Bean,并进行相关配置,例如指定序列化方式、连接池等:
    @Configuration
    public class RedisConfig {
    
        @Bean
        public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
            RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
            redisTemplate.setConnectionFactory(redisConnectionFactory);
            // 设置序列化方式
            redisTemplate.setDefaultSerializer(new StringRedisSerializer());
            redisTemplate.setKeySerializer(new StringRedisSerializer());
            redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
            redisTemplate.setHashKeySerializer(new StringRedisSerializer());
            redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
            redisTemplate.afterPropertiesSet();
            return redisTemplate;
        }
    }
    
    1. 使用Redis:在业务逻辑中注入RedisTemplate,然后通过它进行操作。
    @Service
    public class MyService {
    
        private final RedisTemplate<String, Object> redisTemplate;
    
        public MyService(RedisTemplate<String, Object> redisTemplate) {
            this.redisTemplate = redisTemplate;
        }
    
        public void storeData(String key, Object value) {
            redisTemplate.opsForValue().set(key, value);
        }
    
        public Object getData(String key) {
            return redisTemplate.opsForValue().get(key);
        }
    }
    

    这样你就可以在其他组件中注入MyService,并使用它进行Redis操作了。

    以上就是在Spring Boot中使用Redis的基本步骤。你可以根据具体需求,使用不同的Redis数据结构和操作方法来满足你的业务需求。

    1年前 0条评论
  • worktile的头像
    worktile
    Worktile官方账号
    评论

    Spring Boot 是一个用于构建独立的、生产级别的 Spring 应用程序的框架,它提供了快速启动和开箱即用的功能。Redis 是一个开源的内存数据结构存储系统,可用作数据库、缓存和消息代理。在 Spring Boot 中使用 Redis 可以实现缓存、分布式锁、消息队列等功能。

    下面是在 Spring Boot 中使用 Redis 的一些基本步骤:

    1. 引入 Redis 依赖:在 Maven 的配置文件中添加 Redis 的依赖项,例如:
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    
    1. 配置 Redis 连接信息:在配置文件中设置 Redis 的连接信息,包括主机名、端口号、密码等。配置示例:
    spring:
      redis:
        host: localhost
        port: 6379
        password: password
    
    1. 使用 RedisTemplate:通过 RedisTemplate 类操作 Redis 数据库。可以在 Spring Boot 的配置类中创建 RedisTemplate 的 bean,并配置连接工厂和序列化等参数。示例代码如下:
    @Configuration
    public class RedisConfig {
        
        @Autowired
        private RedisConnectionFactory redisConnectionFactory;
        
        @Bean
        public RedisTemplate<String, Object> redisTemplate() {
            RedisTemplate<String, Object> template = new RedisTemplate<>();
            template.setConnectionFactory(redisConnectionFactory);
            template.setKeySerializer(new StringRedisSerializer());
            template.setValueSerializer(new Jackson2JsonRedisSerializer(Object.class));
            return template;
        }
    }
    
    1. 使用注解操作 Redis:可以使用 Spring Data Redis 提供的注解来简化对 Redis 的操作。例如,使用 @Cacheable、@CachePut、@CacheEvict 等注解来实现缓存功能。示例代码:
    @Service
    public class UserService {
        
        @Autowired
        private RedisTemplate<String, Object> redisTemplate;
        
        @Cacheable(value = "users", key = "#id")
        public User getUserById(String id) {
            // 从数据库中获取用户信息
            User user = userRepository.findById(id);
            return user;
        }
        
        @CachePut(value = "users", key = "#user.id")
        public User saveUser(User user) {
            // 保存用户信息到数据库
            User savedUser = userRepository.save(user);
            return savedUser;
        }
        
        @CacheEvict(value = "users", key = "#id")
        public void deleteUserById(String id) {
            // 从数据库中删除用户信息
            userRepository.deleteById(id);
        }
    }
    
    1. 使用 Redisson 操作 Redis:Redisson 是一个基于 Redis 的 Java 驱动程序,提供了一些常用的分布式功能,如分布式锁、分布式集合等。可以通过引入 Redisson 的依赖来使用它。示例代码:
    <dependency>
        <groupId>org.redisson</groupId>
        <artifactId>redisson-spring-boot-starter</artifactId>
        <version>3.15.0</version>
    </dependency>
    
    @Service
    public class OrderService {
        
        @Autowired
        private RedissonClient redissonClient;
        
        public void placeOrder(String orderId) {
            // 使用分布式锁
            RLock lock = redissonClient.getLock("order:lock:" + orderId);
            try {
                boolean locked = lock.tryLock(5, 10, TimeUnit.SECONDS);
                if (locked) {
                    // 执行订单相关操作
                } else {
                    throw new RuntimeException("无法获取分布式锁");
                }
            } catch (InterruptedException e) {
                throw new RuntimeException("获取分布式锁被中断");
            } finally {
                lock.unlock();
            }
        }
    }
    

    以上是在 Spring Boot 中使用 Redis 的基本步骤,通过配置依赖、连接信息和操作 RedisTemplate 或 Redisson,可以方便地在 Spring Boot 应用程序中使用 Redis 实现各种功能。

    1年前 0条评论
  • fiy的头像
    fiy
    Worktile&PingCode市场小伙伴
    评论

    一、准备工作

    1. 在pom.xml文件中添加以下依赖:
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    
    1. application.properties文件中配置Redis的连接信息:
    # Redis主机地址
    spring.redis.host=localhost
    # Redis端口号
    spring.redis.port=6379
    # Redis密码(如果没有密码,可以不配置)
    spring.redis.password=
    

    二、使用RedisTemplate操作Redis

    1. 创建Redis配置类,配置Redis连接工厂和RedisTemplate:
    @Configuration
    public class RedisConfig {
    
        @Bean
        public JedisConnectionFactory jedisConnectionFactory() {
            RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
            config.setHostName("localhost");
            config.setPort(6379);
            return new JedisConnectionFactory(config);
        }
    
        @Bean
        public RedisTemplate<String, Object> redisTemplate() {
            RedisTemplate<String, Object> template = new RedisTemplate<>();
            template.setConnectionFactory(jedisConnectionFactory());
            return template;
        }
    }
    
    1. 创建业务类,通过注入RedisTemplate来操作Redis:
    @Service
    public class RedisService {
    
        @Autowired
        private RedisTemplate<String, Object> redisTemplate;
    
        public void put(String key, Object value) {
            redisTemplate.opsForValue().set(key, value);
        }
    
        public Object get(String key) {
            return redisTemplate.opsForValue().get(key);
        }
    
        public void delete(String key) {
            redisTemplate.delete(key);
        }
    }
    
    1. 在Controller中使用RedisService来操作Redis:
    @RestController
    public class UserController {
    
        @Autowired
        private RedisService redisService;
    
        @PostMapping("/user")
        public void saveUser(@RequestBody User user) {
            redisService.put("user:" + user.getId(), user);
        }
    
        @GetMapping("/user/{id}")
        public User getUser(@PathVariable("id") String id) {
            return (User) redisService.get("user:" + id);
        }
    
        @DeleteMapping("/user/{id}")
        public void deleteUser(@PathVariable("id") String id) {
            redisService.delete("user:" + id);
        }
    }
    

    以上代码演示了在Spring Boot中使用Redis的基本操作,包括存储数据、获取数据和删除数据。你可以根据实际需求,进一步扩展Redis的使用,如使用Hash类型存储复杂数据结构,使用List类型实现消息队列等。

    1年前 0条评论
注册PingCode 在线客服
站长微信
站长微信
电话联系

400-800-1024

工作日9:30-21:00在线

分享本页
返回顶部