SpringBoot整合Redis以及默认Cache

2019-01-10  本文已影响15人  小波同学

人生格言:不敢冒险,才是风险!

Windows下安装redis的步骤:https://www.cnblogs.com/dingguofeng/p/8709476.html

Redis各版本下载地址:http://download.redis.io/releases/

Windows版Redis下载地址:https://github.com/MicrosoftArchive/redis/releases

一、用Spring的Catch做本地JVM级别缓存
1:引入maven依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

2:创建CacheConfig配置类

@Configuration
@EnableCaching//激活缓存
public class CacheConfig {

    @Bean
    public CacheManager cacheManager(){
        SimpleCacheManager cacheManager = new SimpleCacheManager();
        ConcurrentMapCache cache = new ConcurrentMapCache("cache-1");
        ConcurrentMapCache personCache = new ConcurrentMapCache("persons");
        cacheManager.setCaches(Arrays.asList(cache,personCache));
        return cacheManager;
    }
}

3:创建CacheController测试CacheManager是否生效

@RestController
public class CacheController {

    @Autowired
    private CacheManager cacheManager;

    @GetMapping("/save/cache")
    public Map<String,Object> save(@RequestParam String key,@RequestParam String value){
        Cache cache = cacheManager.getCache("cache-1");
        cache.put(key,value);
        Map<String,Object> result = new HashMap<>();
        result.put(key,value);
        return result;
    }
}

创建实体类

public class Person implements Serializable {

    private String id;

    private String name;

    private int age;

    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 int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

4:创建PersonController

@RestController
public class PersonController {

    @Autowired
    private PersonRepository personRepository;

    @PostMapping("/save/person")
    public boolean savePerson(@RequestBody Person person){
        return personRepository.save(person);
    }

    @GetMapping("/find/{id}")
    public Person findPerson(@PathVariable String id){

        return personRepository.findPerson(id);
    }

}

5:创建PersonRepository接口及其实现类
关于Spring的缓存注解这里有篇文章供大家详细阅读:https://www.cnblogs.com/fashflying/p/6908028.html
Spring的常用注解这里也有一篇文章供大家详细阅读:https://www.cnblogs.com/xiangjune/p/6605215.html

@NoRepositoryBean//有这个注解,spring不会去实例化该接口为repository
public interface PersonRepository {

    @Cacheable(cacheNames = "persons")
    //@Cacheable注解,Spring会在其被调用后将其返回值缓存起来,
        // 以保证下次利用同样的参数来执行该方法时可以直接从缓存中获取结果
    Person findPerson(String id);

    boolean save(Person perosn);
}



@Repository
public class PersonRepositoryImpl implements PersonRepository {

    private final Map<String,Person> repository = new HashMap<>();

    @Override
    public Person findPerson(String id) {
        return repository.get(id);
    }

    @Override
    public boolean save(Person person) {
        return repository.put(person.getId(),person) == null;
    }
}

好了上面利用Spring本身的Cache的缓存功能全部实现,下面是是RedisTemplate的形式实现缓存

二、Spring Boot整合Redis,利用RedisTemplate的形式实现缓存
1:首先增加maven依赖:

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

2:增加redis的application.properties配置
这里有redis的java配置类配置大家可以参考:https://www.cnblogs.com/hlhdidi/p/7928074.html

########################################################
###Redis (RedisConfiguration)
########################################################
# Redis数据库索引(默认为0)
spring.redis.database=1
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=5000

3:在前面的基础上更改PersonRepository接口及其实现类

public interface PersonRepository {

    Person findPerson(String id);

    boolean save(Person perosn);
}



@Repository
public class PersonRepositoryImpl implements PersonRepository {

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public Person findPerson(String id) {
        return (Person)redisTemplate.opsForValue().get(id);
    }

    @Override
    public boolean save(Person person) {
        redisTemplate.opsForValue().set(person.getId(),person);
        return true;
    }
}

RedisTemplate API介绍:
https://www.cnblogs.com/shamo89/p/8622152.html

https://www.jianshu.com/p/7bf5dc61ca06/

好了到这里就整合完毕,也都达到了缓存的需求,此文章为本人原创,如和其他大神博客有相同之处还望见谅!

上一篇下一篇

猜你喜欢

热点阅读