SpringBoot快速上手——《四》:SpringBoot 集成Redis +SpringCache做缓存

SpringBoot 集成Redis +SpringCache做缓存

一.给user加缓存

1.首先创建springboot-redis-cache模块,并把springboot-restful-api的内容复制过来。

2.修改三层架构,即加service层

添加service.UserService接口,再创建实现类service.impl.UserServiceimpl,记得实现类要加上@Service注解。并实现user的增删改查功能。同时将Controller的调用改成UserService。

3.加入redis cache pool等依赖


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

    
      org.springframework.boot
      spring-boot-starter-cache
    

    
      org.apache.commons
      commons-pool2
    
    

4.配置redis

server:
  port: 8090

# 扫描mapper.xml文件
mybatis:
  mapper-locations:
    - classpath:mapping/*.xml
spring:
  application:
    name: springboot-ssm
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/springboot?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: 123zxc
  redis:
    host: 127.0.0.1
    port: 6379
    password: 123zxc
    database: 0
    lettuce:
      pool:
        max-active: 32
        max-wait: 300ms
        max-idle: 16
        min-idle: 8
        

5.启动类加上@EnableCaching注解

6.Service加缓存

@Service
public class UserServiceImpl implements UserService {

    private Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Resource
    private UserMapper userMapper;

    @Override
    @Cacheable(value = "user:id",key = "#id")
    public User getOneUs

你可能感兴趣的:(面试题汇总与解析,java,开发语言,中间件,spring,boot,后端)