springboot项目集成Redis,使用redis各项功能

添加依赖(springboot集成了redis的各项操作)

首先,在项目的pom.xml文件中添加Spring Boot的Redis Starter依赖。



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

<!-- 如果需要使用Redisson作为分布式锁等高级功能,添加如下依赖 -->
<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson-spring-boot-starter</artifactId>
    <version>最新版本</version>
</dependency>

<!-- 其他依赖... -->

配置Redis

properties格式

# application.properties
spring.redis.host=localhost
spring.redis.port=6379

yml格式

# application.yml
spring:
  redis:
    host: localhost
    port: 6379

使用RedisTemplate实现缓存的crud

一旦你添加了上述依赖,Spring Boot会在应用启动时自动配置RedisTemplate,你就可以通过@Autowired注解来注入使用了。
Spring Boot提供了RedisTemplate和StringRedisTemplate来操作Redis

@Service
public class CityServiceImpl implements CityService {

    private static final Logger LOGGER = LoggerFactory.getLogger(CityServiceImpl.class);

    @Autowired
    private CityDao cityDao;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取城市逻辑:
     * 如果缓存存在,从缓存中获取城市信息
     * 如果缓存不存在,从 DB 中获取城市信息,然后插入缓存
     */
    public City findCityById(Long id) {
        // 从缓存中获取城市信息
        String key = "city_" + id;
        ValueOperations<String, City> operations = redisTemplate.opsForValue();

        // 缓存存在
        boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
            City city = operations.get(key);

            LOGGER.info("CityServiceImpl.findCityById() : 从缓存中获取了城市 >> " + city.toString());
            return city;
        }

        // 从 DB 中获取城市信息
        City city = cityDao.findById(id);

        // 插入缓存
        operations.set(key, city, 10, TimeUnit.SECONDS);
        LOGGER.info("CityServiceImpl.findCityById() : 城市插入缓存 >> " + city.toString());

        return city;
    }

    @Override
    public Long saveCity(City city) {
        return cityDao.saveCity(city);
    }

    /**
     * 更新城市逻辑:
     * 如果缓存存在,删除
     * 如果缓存不存在,不操作
     */
    @Override
    public Long updateCity(City city) {
        Long ret = cityDao.updateCity(city);

        // 缓存存在,删除缓存
        String key = "city_" + city.getId();
        boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
            redisTemplate.delete(key);

            LOGGER.info("CityServiceImpl.updateCity() : 从缓存中删除城市 >> " + city.toString());
        }

        return ret;
    }

    @Override
    public Long deleteCity(Long id) {

        Long ret = cityDao.deleteCity(id);

        // 缓存存在,删除缓存
        String key = "city_" + id;
        boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
            redisTemplate.delete(key);

            LOGGER.info("CityServiceImpl.deleteCity() : 从缓存中删除城市 ID >> " + id);
        }
        return ret;
    }

}

使用redis的其他特性功能

  1. 发布订阅
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public void sendMessage(String channel, Object message) {
    redisTemplate.convertAndSend(channel, message);
}
  1. 事务
redisTemplate.execute(new SessionCallback<Object>() {
    @Override
    public Object execute(RedisOperations operations) throws DataAccessException {
        operations.multi();
        operations.opsForValue().set("key1", "value1");
        operations.opsForValue().set("key2", "value2");
        return operations.exec();
    }
});
  1. 分布式锁如果使用Redisson,可以很方便地实现分布式锁。
@Autowired
private RedissonClient redissonClient;
public void lockExample() {
    RLock lock = redissonClient.getLock("myLock");
    lock.lock();
    try {
        // 处理业务逻辑
    } finally {
        lock.unlock();
    }
}

使用redis其他可实现特性

1.限流:使用Redis的INCR命令,为每个请求递增计数。使用EXPIRE命令设置一个过期时间(如60秒)。每次请求时,检查计数器值是否超过限制。
2.分布式Session管理: 将Session数据存储在Redis中,实现分布式Session管理。这样可以确保Session数据在集群中的统一管理和共享。
3.计数器: Redis的原子递增和递减操作可以用来实现计数器功能。比如,你可以使用INCR命令来实现某个操作的调用次数统计。
4.消息队列: Redis的发布/订阅机制可以用作简单的消息队列。你可以将消息发送到指定的频道,然后订阅该频道的客户端将会接收到消息。这在一些简单的异步消息处理场景中非常有用。

相关推荐

  1. springboot项目集成Redis使用redis各项功能

    2024-03-11 22:02:03       23 阅读
  2. SpringBoot集成Redis

    2024-03-11 22:02:03       11 阅读
  3. springboot集成-Redis

    2024-03-11 22:02:03       10 阅读
  4. SpringBoot项目集成Redis+JWT实现系统登录token校验

    2024-03-11 22:02:03       22 阅读
  5. Springboot项目中对Redis使用

    2024-03-11 22:02:03       13 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-11 22:02:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-11 22:02:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-11 22:02:03       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-11 22:02:03       20 阅读

热门阅读

  1. 什么是IoC和AOP?

    2024-03-11 22:02:03       21 阅读
  2. macos系统中redis如何设置密码

    2024-03-11 22:02:03       24 阅读
  3. 为什么农村大学生大多混的很差

    2024-03-11 22:02:03       18 阅读
  4. WPF —— TextBox 控件详解

    2024-03-11 22:02:03       22 阅读
  5. c++ primer中文版第五版作业第十三章

    2024-03-11 22:02:03       19 阅读
  6. C++复习 - String

    2024-03-11 22:02:03       21 阅读
  7. AcWing 5407. 管道(二分,区间合并)

    2024-03-11 22:02:03       18 阅读