【 springboot】springboot 集成redis
1、在pom.xml 中增加相关的jar依赖
<!--加载springboot redis包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、在springboot核心配置文件application.properties 中配置redis 的链接信息
# 配置redis 的连接信息
spring.redis.host=192.168.25.150
spring.redis.port=6379
spring.redis.password=123456
3、配置完上面的步骤,springboot将自动配置redis Template,在需要操作redis的类中注入redis template
例如我们在查询的时候要缓存一下:
实现层代码如下:
package com.cjp.springboot.Service.impl;
import com.cjp.springboot.Service.OrderSertvice;
import com.cjp.springboot.mapper.tb_OrderMapper;
import com.cjp.springboot.model.tb_Order;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
//不要忘记加上service注解
@Service
public class OrderSertviceimpl implements OrderSertvice {
@Autowired
private tb_OrderMapper orderMapper;// 这里的orderMapper会爆红,这是idea的问题,不用管,或者将其改成警告即可
// 注入springboot 自动配置好的redis模板
@Autowired
private RedisTemplate<Object,Object> redisTemplate;
@Override
public List<tb_Order> getAllOrder() {
return orderMapper.getAllOrder();
}
// @Transactional
@Override
public int update() {
tb_Order order =new tb_Order();
order.setOrderId((long) 1);
order.setReceiverAreaName("金燕办公-update");
int update=orderMapper.updateByPrimaryKey(order);
System.out.println(update);
// 因为除数不能为0,所以会有异常,所以上一步会回滚
int a =10/0;
return update;
}
// 用来测试redis连接
@Override
public List<tb_Order> TestRedis() {
List<tb_Order> allOrder=(List<tb_Order>) redisTemplate.opsForValue().get("allOrder");
if (null==allOrder){
// 缓存为空,则查询数据
allOrder= orderMapper.getAllOrder();
// 将数据放到redis中
redisTemplate.opsForValue().set("allOrder",allOrder);
}
System.out.println(allOrder);
return allOrder;
}
}
项目代码访问:https://github.com/NerlCheng/springboot/tree/master/02-springbootmybatis
4、项目启动,如下报错
出现这个错误是因为没有实现order 数据的序列化,否则无法存储到redis中,另外如果不实现序列话,在网络传输的时候也有问题。为此我们需要在model层实现序列化接口:
重启启动即可正常访问了。
还没有评论,来说两句吧...