![9939b113e5864674dc5653adb84b3ed4.png](https://i-blog.csdnimg.cn/blog_migrate/de31cdd525f7994249d955e4c300f39c.jpeg)
在我们使用的微服务的架构中,redis总是能起到关键作用,那么我们在SpringBoot 乃至整个微服务系统中整合redis并使用呢?
整合redis
在我们的Springboot项目中引入redis的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
在配置文件(application.properties或application.yml)中配置redis
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=192.168.0.24
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=200
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=10
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=1000
定义redis操作类接口
public interface RedisService {}
编写实现类
/**
* redis 的工具类
*/
@Service("redisService")
@Transactional(rollbackFor = Exception.class)
public class RedisServiceImpl implements RedisService {
}
在实现类中,我们可以直接也能用redis依赖中的RedisTemplate,我们没有在配置文件或配置类中进行声明,但是我们可以直接的去获取到这个对象的实例,这里不懂的同学可以参考
Spring Boot详解(1)自动配置mp.weixin.qq.com @Autowired
private RedisTemplate<String, ?> redisTemplate;
这个对象就包含redis的所有操作,但是我们进行业务处理的时候还是要对其进行加工,下面是基本的get和set方法
@Override
public boolean set(final String key, final String value) throws Exception {
Assert.hasText(key,"Key is not empty.");
boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
@Override
public Boolean doInRedis(Red