springboot项目redisTemplate快速有效操作redis

简单介绍一下这个redisTemplate吧,目前我也是只接触了一小块,但是项目中已经实际操作ok了。

这次分享主要介绍在springBoot中整合redisTemplate,暂时只针对字符串进行操作;

RedisTemplate介绍

spring封装了RedisTemplate对象来进行对redis的各种操作,它支持所有的 redis 原生的api。

RedisTemplate中定义了对5种数据结构操作

redisTemplate.opsForValue();//操作字符串
redisTemplate.opsForHash();//操作hash
redisTemplate.opsForList();//操作list
redisTemplate.opsForSet();//操作set
redisTemplate.opsForZSet();//操作有序set

废话不多说,直接开始贴代码了。

pom maven添加redis依赖

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

1.springBoot中配置redis

spring:
  session:
    store-type: redis
  redis:
    database: 0
    host: **.**.**.**
    port: 6379
    #password: **********

2.RedisConfig配置

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.cache.jcache.config.JCacheConfigurerSupport;
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.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by wdd on 2019/3/18.
 *
 * @author wdd
 */

@Configuration
@EnableCaching
public class RedisConfig extends JCacheConfigurerSupport {

    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.database}")
    private int database;
    //@Value("${cache.redis.password}")
    //private String password;

    @Bean
    @Override
    public KeyGenerator keyGenerator() {
        return (target, method, params) -> {
            StringBuilder sb = new StringBuilder();
            sb.append(target.getClass().getSimpleName()).append(".");
            sb.append(method.getName()).append(".");
            for (Object obj : params) {
                if (obj != null) {
                    sb.append(obj.toString());
                }
            }
            return sb.toString();
        };
    }

    @SuppressWarnings("rawtypes")
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
        //设置缓存过期时间s
        //rcm.setDefaultExpiration(120);//秒
        //设置缓存过期时间 秒 30天
        //rcm.setDefaultExpiration(2592000);
        Map<String, Long> expires = new HashMap<>(2);
        expires.put("CommonService", 2592000L * 2);
        rcm.setExpires(expires);
        return rcm;
    }

    @Bean
    public RedisTemplate redisTemplate() {
        JedisConnectionFactory factory = new JedisConnectionFactory();
        factory.setHostName(host);
        //factory.setPassword(password);
        factory.setPort(port);
        factory.setDatabase(database);
        factory.afterPropertiesSet();
        StringRedisTemplate template = new StringRedisTemplate(factory);
        FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer(Object.class);
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteClassName);
        fastJsonRedisSerializer.setFastJsonConfig(fastJsonConfig);
        template.setValueSerializer(fastJsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

}

开始实际操作,这里介绍两种方式(1.注解方法方式。2.使用k-value方式进行存储与获取)

一、 k-value方式:

注入RedisTemplate ,切记不可new的方式调用,否则会注入失败,操作失败

import org.springframework.data.redis.core.RedisTemplate;//类地址
@Resource
private RedisTemplate redisTemplate;

保存数据至redis中

                        
//参数介绍:key,value,存储时间,时间类型(TimeUnit支持日,时,分,秒,毫秒)
//set void set(K key, V value, long timeout, TimeUnit unit);
//TimeUnit.DAYS 日 的工具类 
//TimeUnit.HOURS 时 的工具类 
//TimeUnit.MINUTES 分 的工具类 
//TimeUnit.SECONDS 秒 的工具类 
//TimeUnit.MILLISECONDS 毫秒 的工具类
redisTemplate.opsForValue().set("registerMobiles:sendSms"+mobiles,code,3*60, TimeUnit.SECONDS);

 //从缓存中获取验证码信息
 Object verificationCodeRedis = redisTemplate.opsForValue().get("registerMobiles:sendSms"+mobiles);
//由于设置的是180秒失效,180秒之内查询有结果,180秒之后返回为null

二、方法注解方式:

@CacheConfig(cacheNames = "CommonService")//Service实现类上方注解;


    @Override
    @Cacheable
    public String influencePersons() {
        //业务逻辑处理。。。
		//最终会将结果存入redis中
        return "";
    }

好了,代码就这么多,

如果有问题请及时留言,我会第一时间反馈,也可添加我的qq:983469079 


版权声明:本文为Xiaodongge521原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。