SpringBoot】Spring Boot 项目的打包配置

SpringBoot配置Redis指南🚀

Redis作为高性能的内存数据库,在SpringBoot项目中广泛用于缓存、会话存储等场景。下面让我们看看如何轻松配置Redis吧!✨

1.添加依赖📦

首先在`pom.xml`中添加Redis相关依赖:

```xml

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

```

2.配置连接信息⚙️

在`application.yml`或`application.properties`中配置Redis连接:

```yaml
spring:
redis:
host:localhostRedis服务器地址
port:6379Redis服务器端口
password:密码(没有可不填)
database:0使用的数据库索引
timeout:5000连接超时时间(毫秒)
```

3.自定义配置类🛠️

可以创建配置类自定义RedisTemplate:

```java
@Configuration
publicclassRedisConfig{

@Bean
publicRedisTemplateredisTemplate(RedisConnectionFactoryfactory){
RedisTemplatetemplate=newRedisTemplate<>();
template.setConnectionFactory(factory);

//设置key的序列化方式
template.setKeySerializer(newStringRedisSerializer());
//设置value的序列化方式
template.setValueSerializer(newGenericJackson2JsonRedisSerializer());

returntemplate;
}
}
```

4.使用RedisTemplate操作Redis🔥

在Service中注入RedisTemplate即可使用:

```java
@Service
publicclassCacheService{

@Autowired
privateRedisTemplateredisTemplate;

publicvoidsetValue(Stringkey,Objectvalue){
redisTemplate.opsForValue().set(key,value);
}

publicObjectgetValue(Stringkey){
returnredisTemplate.opsForValue().get(key);
}

//更多操作...
}
```

5.使用注解缓存💡

SpringBoot还提供了方便的缓存注解:

```java
@Service
publicclassUserService{

@Cacheable(value="user",key="id")
publicUsergetUserById(Longid){
//模拟数据库查询
returnuserRepository.findById(id).orElse(null);
}

@CacheEvict(value="user",key="id")
publicvoiddeleteUser(Longid){
userRepository.deleteById(id);
}
}
```

记得在启动类上添加`@EnableCaching`注解启用缓存功能哦!✅

总结🎯

通过以上步骤,我们就能在SpringBoot项目中轻松集成Redis了。Redis不仅能提升系统性能,还能实现分布式锁、计数器等实用功能,是开发中的利器!💪

相关推荐
根目录下的猫34 分钟前
RK3588适配的轻量级AI模型推荐
人工智能·后端·python·目标检测
景熙552341 分钟前
15.Java 8 Stream 流入门到实战
java·开发语言·数据结构
wno7041 小时前
Spring Security权限控制
java·python·spring
星栈1 小时前
用 Rust 写 Agent 服务 -- adk-rust 上手记
后端·agent
杨运交2 小时前
[071][验证码模块]基于Spring拦截器的验证码认证设计思想
java·后端·spring
Geek-Chow2 小时前
CountDownLatch in Java
java
LucianaiB2 小时前
我用豆包工作 Seed-2.1-pro,复刻了 QQ 时代爆红的魔术图片
后端
码事漫谈3 小时前
智谱 ZCode 静默上传 Git 历史:48 小时信任危机复盘
后端
SL_staff3 小时前
从RBAC到场景化授权:《无忧·企业文档》三级权限模型的技术实践解析
java·开源·产品
掘金码甲哥3 小时前
当对话模型遇上向量模型,vllm production stack 又该如何应对?
后端