资讯 小学 初中 高中 语言 会计职称 学历提升 法考 计算机考试 医护考试 建工考试 教育百科
栏目分类:
子分类:
返回
空麓网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
空麓网 > 计算机考试 > 软件开发 > 后端开发 > Java

springboot整合redis

Java 更新时间: 发布时间: 计算机考试归档 最新发布

springboot整合redis

springboot整合redis

  • 1.pom.xml依赖引入
  • 2.application.yml配置
  • 3.配置类
    • (1)redis的序列化器(采用fastjson)
    • (2)创建redisTemplate
  • 4.将redisTemplate封装到工具类中(可选)
  • 5.测试

1.pom.xml依赖引入

        
        
            org.springframework.boot
            spring-boot-starter-data-redis
        
        
        
            com.alibaba
            fastjson
            1.2.33
        
        
		
			org.apache.commons
			commons-pool2
		

2.application.yml配置

简单版:

无需引入commons-pool2依赖

spring:
  redis:
    host: xxx.xxx.xxx.xxx
    port: 6379
    database: 0
    password: xxxxxx

复杂版:

需要引入commons-pool2依赖(配置连接池需要)

spring:
  # redis配置
  redis:
    #服务器地址
    host: xxx.xxx.xxx.xxx
    #端口
    port: 6379
    #数据库
    database: 0
    #超时时间
    timeout: 10000ms
    #密码
    password: xxxx
    lettuce:
      pool:
        #最大连接数,默认8
        max-active: 8
        #最大连接阻塞等待时间,默认-1
        max-wait: 10000ms
        #最大空闲连接,默认8
        max-idle: 200
        #最小空闲连接,默认0
        min-idle: 5

3.配置类

redis的序列化器和redis的配置类均放在config包下

(1)redis的序列化器(采用fastjson)

需要引入fastjson依赖

public class FastJsonRedisSerializer implements RedisSerializer
{

    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    private Class clazz;

    static
    {
        ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
    }

    public FastJsonRedisSerializer(Class clazz)
    {
        super();
        this.clazz = clazz;
    }

    @Override
    public byte[] serialize(T t) throws SerializationException
    {
        if (t == null)
        {
            return new byte[0];
        }
        return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException
    {
        if (bytes == null || bytes.length <= 0)
        {
            return null;
        }
        String str = new String(bytes, DEFAULT_CHARSET);

        return JSON.parseObject(str, clazz);
    }


    protected JavaType getJavaType(Class clazz)
    {
        return TypeFactory.defaultInstance().constructType(clazz);
    }
}

(2)创建redisTemplate

方式一:使用fastjson做序列化的方式

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory)
    {
        RedisTemplate template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        FastJsonRedisSerializer serializer = new FastJsonRedisSerializer(Object.class);

        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(serializer);

        // Hash的key也采用StringRedisSerializer的序列化方式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(serializer);

        template.afterPropertiesSet();
        return template;
    }
}

方式二:不使用fastjson做序列化的方式

无需创建FastJsonRedisSerializer类
无需引入fastjson

	@Bean
	public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
		RedisTemplate redisTemplate = new RedisTemplate<>();
		//key序列化
		redisTemplate.setKeySerializer(new StringRedisSerializer());
		//value序列化
		redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
		//hash类型 key序列化
		redisTemplate.setHashKeySerializer(new StringRedisSerializer());
		//hash类型 value序列化
		redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
		//注入连接工厂
		redisTemplate.setConnectionFactory(redisConnectionFactory);
		return redisTemplate;
	}

4.将redisTemplate封装到工具类中(可选)

@Component
public class RedisCache
{
    @Autowired
    public RedisTemplate redisTemplate;

    
    public  void setCacheObject(final String key, final T value)
    {
        redisTemplate.opsForValue().set(key, value);
    }

    
    public  void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit)
    {
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }

    
    public boolean expire(final String key, final long timeout)
    {
        return expire(key, timeout, TimeUnit.SECONDS);
    }

    
    public boolean expire(final String key, final long timeout, final TimeUnit unit)
    {
        return redisTemplate.expire(key, timeout, unit);
    }

    
    public  T getCacheObject(final String key)
    {
        ValueOperations operation = redisTemplate.opsForValue();
        return operation.get(key);
    }

    
    public boolean deleteObject(final String key)
    {
        return redisTemplate.delete(key);
    }

    
    public long deleteObject(final Collection collection)
    {
        return redisTemplate.delete(collection);
    }

    
    public  long setCacheList(final String key, final List dataList)
    {
        Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
        return count == null ? 0 : count;
    }

    
    public  List getCacheList(final String key)
    {
        return redisTemplate.opsForList().range(key, 0, -1);
    }

    
    public  BoundSetOperations setCacheSet(final String key, final Set dataSet)
    {
        BoundSetOperations setOperation = redisTemplate.boundSetOps(key);
        Iterator it = dataSet.iterator();
        while (it.hasNext())
        {
            setOperation.add(it.next());
        }
        return setOperation;
    }

    
    public  Set getCacheSet(final String key)
    {
        return redisTemplate.opsForSet().members(key);
    }

    
    public  void setCacheMap(final String key, final Map dataMap)
    {
        if (dataMap != null) {
            redisTemplate.opsForHash().putAll(key, dataMap);
        }
    }

    
    public  Map getCacheMap(final String key)
    {
        return redisTemplate.opsForHash().entries(key);
    }

    
    public  void setCacheMapValue(final String key, final String hKey, final T value)
    {
        redisTemplate.opsForHash().put(key, hKey, value);
    }

    
    public  T getCacheMapValue(final String key, final String hKey)
    {
        HashOperations opsForHash = redisTemplate.opsForHash();
        return opsForHash.get(key, hKey);
    }

    
    public void delCacheMapValue(final String key, final String hkey)
    {
        HashOperations hashOperations = redisTemplate.opsForHash();
        hashOperations.delete(key, hkey);
    }

    
    public  List getMultiCacheMapValue(final String key, final Collection hKeys)
    {
        return redisTemplate.opsForHash().multiGet(key, hKeys);
    }

    
    public Collection keys(final String pattern)
    {
        return redisTemplate.keys(pattern);
    }
}
 

5.测试

@SpringBootTest
public class TestClass {

    @Autowired
    RedisCache redisCache;

    @Test
    public void f01(){

        redisCache.setCacheObject("k1","博主最帅");
        String k1 = (String)redisCache.getCacheObject("k1");
        System.out.println("==========================");
        System.out.println(k1);

    }
}

转载请注明:文章转载自 http://www.konglu.com/
免责声明:

我们致力于保护作者版权,注重分享,被刊用文章【springboot整合redis】因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理,本文部分文字与图片资源来自于网络,转载此文是出于传递更多信息之目的,若有来源标注错误或侵犯了您的合法权益,请立即通知我们,情况属实,我们会第一时间予以删除,并同时向您表示歉意,谢谢!

我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2023 成都空麓科技有限公司

ICP备案号:蜀ICP备2023000828号-2