springboot+redis實現緩存數據

  在當前互聯網環境下,緩存隨處可見,利用緩存能夠很好的提高系統性能,特別是對於查詢操做,能夠有效的減小數據庫壓力,Redis 是一個開源(BSD許可)的,內存中的數據結構存儲系統,它能夠用做數據庫、緩存和消息中間件,Redis 的優點包括它的速度、支持豐富的數據類型、操做原子性,以及它的通用性。SpringBoot:一款Spring框架的子框架,也能夠叫微服務框架,SpringBoot充分利用了JavaConfig的配置模式以及「約定優於配置」的理念,可以極大的簡化基於SpringMVC的Web應用和REST服務開發。本篇介紹註解方式在springboot項目中使用redis作緩存。java

  一、在pom.xml中引入相關依賴web

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

  二、配置redisconfig,在實際項目中能夠經過配置KeyGenerator來指定緩存信息的key的生成規則redis

package com.example.demo;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    @Bean
    public CacheManager cacheManager(@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
        RedisCacheManager rm = new RedisCacheManager(redisTemplate);
        rm.setDefaultExpiration(30l);// 設置緩存時間
        return rm;
    }

    // @Bean
    // public KeyGenerator myKeyGenerator(){
    // return new KeyGenerator() {
    // @Override
    // public Object generate(Object target, Method method, Object... params) {
    // StringBuilder sb = new StringBuilder();
    // sb.append(target.getClass().getName());
    // sb.append(method.getName());
    // for (Object obj : params) {
    // sb.append(obj.toString());
    // }
    // return sb.toString();
    // }
    // };
    //
    // }

    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        @SuppressWarnings({ "rawtypes", "unchecked" })
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}

  三、建立實體類spring

package com.example.demo;

public class User {

    public User() {
    }
    
    private int id;
    private String name;
    private int age;
    public User(int id, String name, int age) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
    }
    public int getId() {
        return id;
    }
    public void setId(int 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;
    }
    
}

  四、service類,使用註解來作緩存docker

package com.example.demo;

import java.util.Date;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    // @Cacheable緩存key爲name的數據到緩存usercache中
    @Cacheable(value = "usercache", key = "#p0")
    public User findUser(String name) {
        System.out.println("無緩存時執行下面代碼,獲取zhangsan,Time:" + new Date().getSeconds());
        return new User(1, "zhangsan", 13);// 模擬從持久層獲取數據
    }

    // @CacheEvict從緩存usercache中刪除key爲name的數據
    @CacheEvict(value = "usercache", key = "#p0")
    public void removeUser(String name) {
        System.out.println("刪除數據" + name + ",同時清除對應的緩存");
    }

    // @CachePut緩存新增的數據到緩存usercache中
    @CachePut(value = "usercache", key = "#p0")
    public User save(String name, int id) {
        System.out.println("添加lisi用戶");
        return new User(2, "lisi", 13);
    }

    @Cacheable(value = "usercache", key = "#p0")
    public User findUser2(String name) {
        System.out.println("無緩存時執行下面代碼,獲取lisi,Time:" + new Date().getSeconds());
        return new User(2, "lisi", 13);// 模擬從持久層獲取數據
    }
}

  五、控制器類數據庫

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @Autowired
    UserService userService;

    @GetMapping("/finduser1")
    public User finduser1() {
        return userService.findUser("zhangsan");
    }

    @GetMapping("/finduser2")
    public User finduser2() {
        return userService.findUser2("lisi");
    }

    @GetMapping("/adduser2")
    public User adduser2() {
        return userService.save("lisi", 13);
    }

    @GetMapping("/delete")
    public void removeUser() {
        userService.removeUser("zhangsan");
    }
}

  六、配置信息,這裏使用docker在本地虛擬機啓動一個redis服務緩存

spring.redis.database=0
spring.redis.host=192.168.86.133
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

  啓動redis服務,而後啓動本springboot項目,經過訪問對應的url,能夠看到在進行數據增刪改查的時候是有緩存的。springboot

相關文章
相關標籤/搜索