Spring Boot 整合redis

整合redis

  • 实体类须要序列化
  • 额外配置依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-reis</artifactId>
</dependency>
复制代码
  • 经过配置文件配置
#配置redis
spring.redis.host=192.168.243.129
spring.redis.port=6379
spring.redis.database=0
spring.redis.password=bisnow

#配置cache
spring.cache.cache-names=c1

复制代码
  • 启动器开启缓存自动配置
@SpringBootApplication
@EnableCaching
public class RediscacheApplication {
复制代码
  • 此处模拟数据库操做
@Service
// 配置缓存名称,不是必须的,能够在每一次启动时指定
@CacheConfig(cacheNames = "c1")
public class UserService {
    /** * @Cacheable 将当前方法的返回值缓存起来 * 缓存的key就是方法的参数,方法返回值是value * * 若是多个参数,同时做为key(必须都知足才能取出缓存) * 多参数指定某个参数为key 须要手动配置 * @Cacheable(key = "id") 表示只用id做为key * @param id * @return */
    @Cacheable(key = "#id")
    public User getUserById(Long id,String username){
        System.out.println(id);
        User user = new User();
        user.setId(id);
        return user;
    }
    /** * 删除 * allEntries 默认为false,表示根据key删除而不是全删除缓存 * beforeInvocation 默认为false 表示先删除数据,后清除缓存 * @param id */
    //这个注解通常加在删除方法上,表示同步删除缓存中的数据
    @CacheEvict(allEntries = false,beforeInvocation = false)
    public void deleteById(Long id){
        //在这里执行删除操做,去数据库中删除
        //正常的逻辑:首先去数据库中删除,而后去缓存中删除
    }

    /** * 更新 * @CachePut 这个注解通常用在修改方法上 * 表示修改数据库数据的同时也修改缓存 * 更新方法必须有返回值 * geng * @param id * @return */
    @CachePut
    public User updateById(Long id){
        User user = new User();
        user.setId(99L);
        user.setUsername("李四");
        return user;
    }
}

复制代码
  • 测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class RediscacheApplicationTests {
    @Autowired
    UserService userService;

    @Test
    public void test1(){
        User userById = userService.getUserById(99L,"");
        System.out.println("userbyid >>> 1:" +userById);
        User userById2 = userService.getUserById(99L,"");
        System.out.println("uuerbyid >>> 2:" + userById2);
    }

    @Test
    public void test2(){
        User userById1 = userService.getUserById(99L,"");
        System.out.println("uuerbyid >>> 1:" + userById1);
        userService.deleteById(99L);
        User userById2 = userService.getUserById(99L,"");
        System.out.println("uuerbyid >>> 2:" + userById2);
    }

    @Test
    public void test3(){
        User userById = userService.getUserById(99L,"");
        System.out.println("userbyid >>> 1:" +userById);
        userService.updateById(99L);
        User userById2 = userService.getUserById(99L,"");
        System.out.println("uuerbyid >>> 2:" + userById2);
    }
}
复制代码
相关文章
相关标签/搜索