SpringBoot之使用Redis做缓存

原创
2017/02/04 09:11
阅读数 207

刚看了一篇博客,《SpringBoot缓存注解学习笔记之Redis》,因为是Redis的,而且之前一直想用redis做缓存,而且也写了一些工具类,看了这篇博客后发现自己TMD又造了轮子,可恨之余又惊喜万分,故编码实习之。

但中途遇到一些问题,按照该文的步骤是行不通的,因为缺了几个很关键的配置项,这里记此一文,以供日后参考。

首先是Maven的pom.xml设置:

<!-- 单元测试相关 -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
</dependency>

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

<!-- cache -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

这几项是很关键的,没有它,Cache也就无从说起了。

然后是配置application.yml

spring:
  redis:
    host: localhost

这里主要是配置redis连接相关

然后是主体代码:

实体定义 Person.java

package cn.sanlea.study.redis;

import java.io.Serializable;
import java.util.Objects;

public class Person implements Serializable
{
    private String id;

    private String name;

    public Person(String id, String name)
    {
        this.id = id;
        this.name = name;
    }

    public String getId()
    {
        return id;
    }

    public void setId(String id)
    {
        this.id = id;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public Person()
    {
    }

    @Override
    public boolean equals(Object o)
    {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return Objects.equals(id, person.id);
    }

    @Override
    public int hashCode()
    {
        return Objects.hash(id);
    }
}

实体仓库定义 PersonRepository.java

package cn.sanlea.study.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Component
public class PersonRepository
{
    private Logger logger = LoggerFactory.getLogger(PersonRepository.class);
    private List<Person> persons;

    public PersonRepository()
    {
        persons = new ArrayList<>();
    }

    public Person create(String name)
    {
        Person person = new Person(UUID.randomUUID().toString(), name);
        persons.add(person);

        logger.info("Person `{}` created -> {}", name, person.getId());

        return person;
    }

    public Person find(String id)
    {
        logger.info("Find person for id: {}", id);
        for (Person person : persons)
        {
            if (person.getId().equals(id))
            {
                return person;
            }
        }

        return null;
    }

    public void update(String id, String name)
    {
        Person person = find(id);
        if (person == null)
        {
            return;
        }

        person.setName(name);
    }

    public void delete(String id)
    {
        Person person = find(id);
        if (person == null)
        {
            return;
        }

        persons.remove(person);
    }
}

管理类 PersonManager.java

package cn.sanlea.study.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

@Component
public class PersonManager
{
    private final PersonRepository repository;

    @Autowired
    public PersonManager(PersonRepository repository)
    {
        this.repository = repository;
    }

    public Person create(String name)
    {
        return repository.create(name);
    }

    // 这里使用参数id作为缓存key
    @Cacheable(key = "#id", cacheNames = "person")
    public Person find(String id)
    {
        return repository.find(id);
    }

    // 这里使用参数id作为缓存key
    @CachePut(key = "#id", cacheNames = "person")
    public void update(String id, String name)
    {
        repository.update(id, name);
    }

    // 这里使用参数id作为缓存key
    @CacheEvict(key = "#id", cacheNames = "person")
    public void delete(String id)
    {
        repository.delete(id);
    }
}

程序入口 Entrance.java

package cn.sanlea.study.redis;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class Entrance
{
    public static void main(String[] args)
    {
        SpringApplication.run(Entrance.class, args);
    }
}

然后是测试代码

import cn.sanlea.study.redis.Entrance;
import cn.sanlea.study.redis.Person;
import cn.sanlea.study.redis.PersonManager;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static junit.framework.TestCase.assertNotNull;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Entrance.class)
public class RedisCacheTest
{
    @Autowired
    private PersonManager manager;

    @Test
    public void testFind()
    {
        Person person = manager.create("kut");
        assertNotNull(person);

        String id = person.getId();
        person = manager.find(id);
        person = manager.find(id);
        person = manager.find(id);
        person = manager.find(id);
        person = manager.find(id);
    }

    @Test
    public void testUpdate()
    {
        Person person = manager.create("kut");
        assertNotNull(person);

        String id = person.getId();
        person = manager.find(id);
        person = manager.find(id);

        manager.update(id, "magick");
        person = manager.find(id);
        person = manager.find(id);
    }

    @Test
    public void testDelete()
    {
        Person person = manager.create("kut");
        assertNotNull(person);

        String id = person.getId();
        person = manager.find(id);
        person = manager.find(id);

        manager.delete(id);
        person = manager.find(id);
        person = manager.find(id);
    }
}

打完收工。

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部