缓存SpringHome技术专题

spring boot —— redis 缓存注解使用教程

2018-07-12  本文已影响331人  wine_5664

spring boot —— redis 缓存注解使用教程

示例项目地址:https://github.com/14251104246/spring-boot-redis-annotation-demo

依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

配置

spring.cache.type: REDIS

# REDIS (RedisProperties)
spring.redis.database: 0
spring.redis.host: 127.0.0.2
spring.redis.password:
spring.redis.port: 6379
spring.redis.pool.max-idle: 8
spring.redis.pool.min-idle: 0
spring.redis.pool.max-active: 100
spring.redis.pool.max-wait: -1
@Configuration
@EnableAutoConfiguration
@ComponentScan("org.hsweb.demo")
@MapperScan("org.hsweb.demo.dao")
@EnableCaching//开启注解驱动的缓存管理
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

示例项目基本逻辑

.
├── Application.java    //启动类
├── controller 
│   ├── RedisOnlyController.java
│   └── UserController.java
├── dao
│   └── UserDao.java    //mapper接口(mybatis)
├── po
│   └── User.java   // 用户po类
└── service
    ├── impl
    │   ├── RedisOnlyServiceImpl.java
    │   └── SimpleUserService.java
    ├── RedisOnlyService.java
    └── UserService.java

redis 注解使用入门

@Cacheable 注解简单使用教程——用于查询操作接口

@RequestMapping("/redisOnly")
@RestController()
public class RedisOnlyController {
    @Resource
    RedisOnlyService redisOnlyService;
    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
    public User getById(@PathVariable("id") String id) {
        return redisOnlyService.selectById(id);
    }
}

@Service
public class RedisOnlyServiceImpl implements UserService {
    /**
     *  先用id生成key,在用这个key查询redis中有无缓存到对应的值
     *
     *  若无缓存,则执行方法selectById,并把方法返回的值缓存到redis
     *
     *  若有缓存,则直接把redis缓存的值返回给用户,不执行方法
     */
    @Cacheable(cacheNames="user", key="#id")
    @Override
    public User selectById(String id) {
        //直接new一个给定id的用户对象,来返回给用户
        return new User(id,"redisOnly","password");
    }
}
image.png

深入理解@Cacheable注解

graph TB
    A[查询id为9876的用户] -->|RedisOnlyController| B(调用RedisOnlyServiceImpl前被aop拦截)
    B --> C{id为9876的用户数据是否缓存到redis?}
    C -->|是| D[从redis中获取用户数据并立刻返回]
    C -->|否| E[执行service类的selectById方法并缓存结果后返回]

@CacheEvict 注解简单使用教程——用于删除操作接口

@RequestMapping("/redisOnly")
@RestController()
public class RedisOnlyController {
    @RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
    public boolean delete(@PathVariable String id) {
        return redisOnlyService.delete(id);
    }
}

@Service
public class RedisOnlyServiceImpl implements UserService {
    @CacheEvict(cacheNames="user", key="#id")
    @Override
    public boolean delete(String id) {
        // 可以在这里添加删除数据库对应用户数据的操作
        return true;
    }
}

@CachePut 注解简单使用教程——用于删除操作接口

@RequestMapping("/redisOnly")
@RestController()
public class RedisOnlyController {
    @Resource
    RedisOnlyService redisOnlyService;

    @RequestMapping(value = "/user/{id}", method = RequestMethod.PUT)
    public User update(@PathVariable String id, @RequestBody User user) {
        user.setId(id);
        redisOnlyService.update(user);
        return user;
    }
}

@Service
public class RedisOnlyServiceImpl implements UserService {
    // 记录
    private AtomicInteger executeCout = new AtomicInteger(0);

    @CachePut(cacheNames="user", key="#user.id")
    @Override
    public User update(User user) {
        // 每次方法执行executeCout
        user.setUsername("redisOnly" + executeCout.incrementAndGet());
        // 必须把更新后的用户数据返回,这样才能把它缓存到redis中
        return user;
    }
}
image.png
@Cacheable(cacheNames="user", key="#id")
@Override
public User selectById(String id) {
    return new User(id,"redisOnly" + executeCout.incrementAndGet(),"password");
}

redis注解与mybatis一起使用

@Service("userService")
public class SimpleUserService implements UserService {
    @Resource
    private UserDao userDao;
    @Cacheable(cacheNames="user", key="#id")
    @Override
    public User selectById(String id) {
        return userDao.selectById(id);
    }
    @Cacheable(cacheNames="user", key="#username")
    @Override
    public User selectByUserName(String username) {
        return userDao.selectByUserName(username);
    }
    @Override
    public List<User> selectAll() {
        return userDao.selectAll();
    }
    @CachePut(cacheNames="user", key="#user.id")
    @Override
    public User insert(User user) {
        user.setId(UUID.randomUUID().toString());
        userDao.insert(user);
        return user;
    }
    @CachePut(cacheNames="user", key="#user.id")
    @Override
    public User update(User user) {
        userDao.update(user);
        return user;
    }
    @CacheEvict(cacheNames="user", key="#id")
    @Override
    public boolean delete(String id) {
        return userDao.deleteById(id) == 1;
    }
}

redis 注解的其他知识点

测试

上一篇下一篇

猜你喜欢

热点阅读