spring boot 集成redis

第一步:redis

確定要有redis數據庫,在本地或者在某臺服務器上。我是在本機(windows7)安裝的。在dos窗口進入該文件的目錄下,輸入命令:redis-server.exe redis.windows.conf啓動服務 若是有個redis的圖形就說明成功了。spring

第二步:數據庫

個人第二步是安裝redis可視化工具redisdesktopmanager,在dos窗口真的不習慣,有可視化工具真的方便不少!就像Navicat同樣的工具windows

第三部:緩存

在我原有的項目集成redis服務器

1.在pom.xml裏引入jar包app

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-redis</artifactId>
    <version>${spring-boot-starter-redis-version}</version>
</dependency>

版本大家看着辦ide

2.在application.properties加入參數spring-boot

# REDIS (RedisProperties)
# Redis數據庫索引(默認爲0)
spring.redis.database=0
# Redis服務器地址
spring.redis.host=127.0.0.1
# Redis服務器鏈接端口
spring.redis.port=6379
# Redis服務器鏈接密碼(默認爲空)
spring.redis.password=
# 鏈接池最大鏈接數(使用負值表示沒有限制)
spring.redis.pool.max-active=8
# 鏈接池最大阻塞等待時間(使用負值表示沒有限制)
spring.redis.pool.max-wait=-1
# 鏈接池中的最大空閒鏈接
spring.redis.pool.max-idle=8
# 鏈接池中的最小空閒鏈接
spring.redis.pool.min-idle=0
# 鏈接超時時間(毫秒)
spring.redis.timeout=0

3工具

@PropertySource(value = "classpath:/application.properties")

引入參數基本就能夠了

我根據別人的例子寫了幾個小例子試了一下

@Configuration
@PropertySource(value = "classpath:/application.properties")
@EnableCaching //啓用緩存,這個註解很重要;
public class RedisCacheConfig extends CachingConfigurerSupport {

    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.timeout}")
    private int timeout;

    @Bean
    public KeyGenerator wiselyKeyGenerator() {
        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 CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
        // Number of seconds before expiration. Defaults to unlimited (0)
        cacheManager.setDefaultExpiration(60); //設置key-value超時時間 秒
        return cacheManager;
    }

    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        setSerializer(template); //設置序列化工具,這樣ReportBean不須要實現Serializable接口
        template.afterPropertiesSet();
        return template;
    }

    private void setSerializer(StringRedisTemplate template) {
        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);
    }

}

先引入redis緩存的參數

@Service
public class RedisdemoService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Cacheable(value = "usercache",keyGenerator = "wiselyKeyGenerator")
    public Users findUser(long id, String nickname, String phone){
        stringRedisTemplate.opsForValue().set("aaa", "111");
        BoundValueOperations<String ,String > bos=stringRedisTemplate.boundValueOps("aaaa");
        bos.set("bbbbbb");
        System.out.println(bos.get());
        System.out.println("第一次緩存 第二次記錄");
        return new Users(id,nickname,phone);
    }
    @Cacheable(value = "token",keyGenerator = "wiselyKeyGenerator")
    public String productToken(){
        stringRedisTemplate.opsForValue().set("aaa", "111");
        stringRedisTemplate.expire("aaa",20, TimeUnit.SECONDS);
       String s= stringRedisTemplate.opsForValue().get("aaa");
        System.out.println(  stringRedisTemplate.opsForValue().get("aaa"));
        BoundValueOperations<String ,String > bos=stringRedisTemplate.boundValueOps("aaaa");
        bos.set("bbbbbb");
        System.out.println(bos.get());
        System.out.println("就打印一次");
        return "12345666+5544554";
    }

}

這裏面都是我試用的參數和方法

能夠在controller兩次調用該servicce的方法你就知道緩存到底有沒有生效。

往redis寫入用RedisTemplate這個類就能夠了, 設置時效都是能夠的,我上面就測試了緩存時效和本身寫入數據庫的鍵值對本身控制時效。還寫了一個生產時效的token的方法

public class ProductToken {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 用來生產有實效的token
     * @param key
     * @param value
     */
    public void prioductToken(String key,String value){
        if(stringRedisTemplate.opsForValue().get(key)==null){
            stringRedisTemplate.opsForValue().set(key,value);//存儲鍵值對
            stringRedisTemplate.expire(key,3600, TimeUnit.SECONDS);//設置超時
        }
        else {
            stringRedisTemplate.expire(key,3600, TimeUnit.SECONDS);//設置超時
        }
    }
}

還沒用於項目,大家看看就行。我就是一步步作的。

資料請看:http://wiselyman.iteye.com/blog/2184884

相關文章
相關標籤/搜索