美文网首页
Java封装操作Redis的工具方法

Java封装操作Redis的工具方法

作者: Mongogo | 来源:发表于2017-12-08 16:02 被阅读0次

SpringBoot中配置Redis的配置代码

package com.example.demo.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.cache.interceptor.SimpleKeyGenerator;
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.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.HashMap;

@Configuration
@EnableCaching
public class RedisConfiguration extends CachingConfigurerSupport {
    /**如果加入@EnableCaching注解则JedisConnectionFactory类直接注入即可*/
    @Autowired
    private JedisConnectionFactory jedisConnectionFactory;

    /**
     * 创建操作Redis的模板类
     * @return 操作Redis的对象
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        /** Jackson2JsonRedisSerializer是JSON到Object对象的序列化/反序列化的类*/
        Jackson2JsonRedisSerializer<Object> 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);

        /**字符串的序列化/反序列化*/
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        /**Java对象的序列化/反序列化*/
//        JdkSerializationRedisSerializer jdkSerializationRedisSerializer = new JdkSerializationRedisSerializer();
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(jedisConnectionFactory);
        redisTemplate.setKeySerializer(stringRedisSerializer);// 设置key使用stringRedisSerializer序列化
        redisTemplate.setHashKeySerializer(stringRedisSerializer);// 设置hashKey使用stringRedisSerializer序列化
//        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setDefaultSerializer(jackson2JsonRedisSerializer);// 设置Value默认的序列化/反序列化
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    /**
     * 缓存管理的类
     * @param redisTemplate 操作Redis的对象
     * @return 缓存管理对象
     */
    @Bean
    public CacheManager cacheManager(RedisTemplate<String, Object> redisTemplate) {
        RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
        redisCacheManager.setDefaultExpiration(100);// 设置默认的缓存过期时间
        HashMap<String, Long> map = new HashMap<>();
        map.put("weixin", 7200L);// 放入value=weixin的过期时间
        redisCacheManager.setExpires(map);// 将map集合放入redis缓存管理中
        return redisCacheManager;
    }

    /**
     * Redis的键Key生成方法
     * @return 键的生成类
     */
    @Override
    @Bean
    public KeyGenerator keyGenerator() {
        return new SimpleKeyGenerator();
    }

//    @Bean
//    @Override
//    public KeyGenerator keyGenerator() {
//        return (target, method, objects) -> {
//            StringBuilder sb = new StringBuilder();
//            sb.append(target.getClass().getName());
//            sb.append("::" + method.getName() + ":");
//            for (Object obj : objects) {
//                sb.append(obj.toString());
//            }
//            return sb.toString();
//        };
//    }
}

在application.yml中填写Redis的相关配置

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: root
    # 最大活跃数
    maxActive: 20
    # 初始化数量
    initialSize: 1
    # 最大连接等待超时时间
    maxWait: 60000
    # 打开PSCache,并且指定每个连接PSCache的大小
    poolPreparedStatements: true
    maxPoolPreparedStatementPerConnectionSize: 20
  # Redis的相关配置
  redis:
  # Redis数据库索引(默认为0)
    database: 0
    # Redis服务器地址
    host: localhost
    # Redis服务器连接端口
    port: 6379
    # Redis服务器连接密码(默认为空)
    password:
    # Redis连接池相关配置
    pool:
    # 连接池最大连接数(使用负值表示没有限制)
      max-active: 8
      # 连接池最大阻塞等待时间(使用负值表示没有限制)
      max-wait: -1
      # 连接池中的最大空闲连接
      max-idle: 8
      # 连接池中的最小空闲连接
      min-idle: 0
      # 连接超时时间(毫秒)
    timeout: 0
  profiles:
    # 设置启用哪个配置文件
    active: dev
  main:
    banner-mode: console
    #禁用banner
  output:
    ansi:
      enabled: always
  cache:
    # 如果在classpath下的根目录可以找到一个名为ehcache.xml的文件,则缓存将使用EhCache 2.x。
    # 如果EhCache 2.x和这样的文件出现,那它们将用于启动缓存管理器,使用以下配置可提供替换的配置文件:
#    ehcache:
#      config: classpath:config/ehcache-spring.xml
    cache-names: mycache
    type: redis
  # 开启aop功能
  aop:
    auto: true
  devtools:
    restart:
      enabled: true
  http:
    multipart:
      max-file-size: 1MB
      max-request-size: 10MB
#  mvc:
#    view:
#      prefix: /
#      suffix: .html
logging:
  #设置日志保存的路径
  path: log
  #设置日志文件名称
  file: logs/spring.log
  level: debug
  #设置日志的配置文件
  config: classpath:config/logback-spring.xml
debug: true
#spring.jpa.properties.hibernate.hbm2ddl.auto=create-drop
#spring.jpa.properties.hibernate.show_sql=true
logging.level.com.example.demo.mapper: debug

相关文章

网友评论

      本文标题:Java封装操作Redis的工具方法

      本文链接:https://www.haomeiwen.com/subject/dkbeixtx.html