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的发布/订阅机制可以用作简单的消息队列。你可以将消息发送到指定的频道,然后订阅该频道的客户端将会接收到消息。这在一些简单的异步消息处理场景中非常有用。
相关推荐
小鱼人爱编程1 小时前
Java基石--反射让你直捣黄龙
前端·spring boot·后端
hqxstudying1 小时前
J2EE模式---服务层模式
java·数据库·后端·spring·oracle·java-ee
GM_8281 小时前
【最新最完整】SpringAI-1.0.0开发MCP Server,搭建MCP Client 实战笔记(进阶+详细+完整代码)
java·后端·ai编程·springai·mcp
程序员爱钓鱼1 小时前
Go语言实战案例-滑动窗口最大值
后端·google·go
Victor3562 小时前
MySQL(163) 如何理解MySQL的隔离级别?
后端
Victor3562 小时前
MySQL(164)如何设置MySQL的隔离级别?
后端
代码老y3 小时前
ASP.NET Core 高并发万字攻防战:架构设计、性能优化与生产实践
后端·性能优化·asp.net
武子康8 小时前
Java-80 深入浅出 RPC Dubbo 动态服务降级:从雪崩防护到配置中心秒级生效
java·分布式·后端·spring·微服务·rpc·dubbo
舒一笑9 小时前
我的开源项目-PandaCoder迎来史诗级大更新啦
后端·程序员·intellij idea
@昵称不存在10 小时前
Flask input 和datalist结合
后端·python·flask