SpringBoot项目集成Redis,使用Redis各项功能

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

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

xml 复制代码
<dependencies>
    <!-- Spring Boot Redis Starter -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId
        <version>YOUR_SPRING_BOOT_VERSION</version>
    </dependency>
    
    <!-- 如果需要使用Redisson作为分布式锁等高级功能,添加如下依赖 -->
    <dependency>
        <groupId>org.redisson</groupId>
        <artifactId>redisson-spring-boot-starter</artifactId>
        <version>最新版本</version>
    </dependency>
    
    <!-- 其他依赖... -->
</dependencies>

配置Redis

properties格式

xml 复制代码
# application.properties
spring.redis.host=localhost
spring.redis.port=6379

yml格式

xml 复制代码
# application.yml
spring:
  redis:
    host: localhost
    port: 6379

使用RedisTemplate实现缓存的crud操作

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

java 复制代码
@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. 发布订阅
java 复制代码
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public void sendMessage(String channel, Object message) {
    redisTemplate.convertAndSend(channel, message);
}
  1. 事务
java 复制代码
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,可以很方便地实现分布式锁。
java 复制代码
@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的发布/订阅机制可以用作简单的消息队列。你可以将消息发送到指定的频道,然后订阅该频道的客户端将会接收到消息。这在一些简单的异步消息处理场景中非常有用。
相关推荐
摸鱼的春哥3 小时前
春哥的Agent通关秘籍07:5分钟实现文件归类助手【实战】
前端·javascript·后端
Victor3563 小时前
MongoDB(2)MongoDB与传统关系型数据库的主要区别是什么?
后端
JaguarJack3 小时前
PHP 应用遭遇 DDoS 攻击时会发生什么 从入门到进阶的防护指南
后端·php·服务端
BingoGo3 小时前
PHP 应用遭遇 DDoS 攻击时会发生什么 从入门到进阶的防护指南
后端
Victor3563 小时前
MongoDB(3)什么是文档(Document)?
后端
牛奔5 小时前
Go 如何避免频繁抢占?
开发语言·后端·golang
想用offer打牌10 小时前
MCP (Model Context Protocol) 技术理解 - 第二篇
后端·aigc·mcp
KYGALYX11 小时前
服务异步通信
开发语言·后端·微服务·ruby
掘了11 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
爬山算法12 小时前
Hibernate(90)如何在故障注入测试中使用Hibernate?
java·后端·hibernate