springBoot整合redis--让缓存成为你系统的一部分

三步上篮

1、导入redis依赖

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

2.编写config

package com.example.demo.config;

import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.*;

import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

/**
 * Redis配置
 *
 * @author chenshun
 * @email [email protected]
 * @date 2017-07-70 19:22
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
    
    @Autowired
    private RedisConnectionFactory factory;


//    RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
//    //定义value的序列化方式
//    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);
//
//        redisTemplate.setKeySerializer(new StringRedisSerializer());
//        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
//        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
//        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
//        redisTemplate.setConnectionFactory(factory);
    @Bean
    @SuppressWarnings("rawtypes")
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new FastJsonRedisSerializer(Object.class));
        redisTemplate.setValueSerializer(new FastJsonRedisSerializer(Object.class));
        redisTemplate.setConnectionFactory(factory);
        return redisTemplate;
    }

    @Bean
    public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForHash();
    }

    @Bean
    public ValueOperations<String, String> valueOperations(RedisTemplate<String, String> redisTemplate) {
        return redisTemplate.opsForValue();
    }

    @Bean
    public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForList();
    }

    @Bean
    public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForSet();
    }

    @Bean
    public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForZSet();
    }
    /**缓存管理器*/
  
    @Primary
    @Bean
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
         //初始化一个RedisCacheWriter
         RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisTemplate.getConnectionFactory());
         //设置CacheManager的值序列化方式为json序列化
         RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair.fromSerializer(new FastJsonRedisSerializer(Object.class));
         RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(pair);

         //设置默认超过时期是1天
         defaultCacheConfig.entryTtl(Duration.ofDays(1));
         //初始化RedisCacheManager
         return new RedisCacheManager(redisCacheWriter, defaultCacheConfig);
    }
}

3.实现redis服务(redis存取调用service)

package com.example.demo.service.redis;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * redis操作Service,
 * 对象和数组都以json形式进行存储
 * Created by macro on 2018/8/7.
 */
public interface RedisService {
    /**
     * 存储数据
     */
    void set(String key, String value);

    void setStringExpire(String key, String value, long expire, TimeUnit timeUnit);

    /**
     * 存储数据
     */
    void setExpire(String key, Object value, long expire);

    /**
     * 获取数据
     */
    String get(String key);

    /**
     * 设置超期时间
     */
    boolean expire(String key, long expire);

    /**
     * 删除数据
     */
    void remove(String key);

    /**
     * 自增操作
     *
     * @param delta 自增步长
     */
    Long increment(String key, long delta);

    <T> T getMapField(String key, String field, Class<T> clazz);

    void delMapField(String key, String... field);

    <T> void addMap(String key, String field, T obj);

    void setMap(String key, Map<Object, Object> value);
    Map<Object, Object> getMap(String key);


}
package com.example.demo.service.redis.impl;


import com.example.demo.service.redis.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * redis操作Service的实现类
 * Created by macro on 2018/8/7.
 */
@Service
public class RedisServiceImpl implements RedisService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void set(String key, String value) {
        stringRedisTemplate.opsForValue().set(key, value);
    }

    @Override
    public void setStringExpire(String key, String value, long expire,TimeUnit timeUnit) {
        stringRedisTemplate.opsForValue().set(key, value);
        stringRedisTemplate.expire(key,expire,timeUnit);
    }

    @Override
    public void setExpire(String key, Object value, long expire) {
        redisTemplate.opsForValue().set(key, value);
        redisTemplate.expire(key, expire, TimeUnit.SECONDS);
    }

    @Override
    public String get(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }

    @Override
    public boolean expire(String key, long expire) {
        return redisTemplate.expire(key, expire, TimeUnit.SECONDS);
    }

    @Override
    public void remove(String key) {
        stringRedisTemplate.delete(key);
    }

    @Override
    public Long increment(String key, long delta) {
        return stringRedisTemplate.opsForValue().increment(key, delta);
    }

    @Override
    public <T> T getMapField(String key, String field, Class<T> clazz) {
        return (T) redisTemplate.boundHashOps(key).get(field);
    }

    @Override
    public void delMapField(String key, String... field) {
        BoundHashOperations<String, String, ?> boundHashOperations = redisTemplate.boundHashOps(key);
        boundHashOperations.delete(field);
    }

    @Override
    public <T> void addMap(String key, String field, T obj) {
        redisTemplate.opsForHash().put(key, field, obj);
    }


    @Override
    public Map<Object, Object> getMap(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    @Override
    public void setMap(String key, Map<Object, Object> value) {
        redisTemplate.opsForHash().putAll(key, value);
    }

}

最后 调用测试

 

 另外 贴个yml中的redis配置

# DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/ispd25?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
    username: root
    password: 123

# Tomcat datasource specific settings
# org.apache.tomcat.jdbc.pool.DataSource  org.apache.tomcat.jdbc.pool.PoolProperties
#初始化连接: 连接池启动时创建的初始化连接数量
    tomcat:
      initial-size: 5
#最大活动连接: 连接池在同一时间能够分配的最大活动连接的数量,如果设置为非正数则表示不限制
      max-active: 60
#最大空闲连接: 连接池中容许保持空闲状态的最大连接数量, 超过的空闲连接将被释放, 如果设置为负数表示不限制
      max-idle: 10
#最小空闲连接: 连接池中容许保持空闲状态的最小连接数量, 低于这个数量将创建新的连接, 如果设置为0则不创建.默认与initialSize相同
      min-idle: 5
# 最大等待时间: 当没有可用连接时, 连接池等待连接被归还的最大时间( 以毫秒计数), 超过时间则抛出异常, 如果设置为-1 表示无限等待单位毫秒
      max-wait: -1
#是否对空闲连接进行校验,如果检测失败, 则连接将被从池中去除.注意: 设置为true 后如果要生效,validationQuery 参数必须设置为非空字符串
      test-while-idle: true
#SQL 查询, 用来验证从连接池取出的连接
      validation-query: SELECT 1
#空闲连接回收器执行间隔,单位毫秒
      time-between-eviction-runs-millis: 310000
# Validate the connection before borrowing it from the pool.
      test-on-borrow: true
#校验查询超时时间以秒为单位
      validation-query-timeout: 10
#避免过度验证,保证验证不超过这个频率——以毫秒为单位
      validation-interval: 30000
#空闲连接能够保持空闲的最小时间,单位毫秒,在这个区间不会被回收器回收
      min-evictable-idle-time-millis: 1200000
#空闲连接回收器的执行线程数
      num-tests-per-eviction-run: 10
#检查连接是否泄漏(一般是因为没有关闭连接),如果他们超过了removeAbandonedTimout 的限制.如果设置为true, 连接被认为是被泄露并且可以被删除,
      remove-abandoned: true
#连接多久没有释放则认为是泄漏线程
      remove-abandoned-timeout: 1800

# JPA (JpaBaseConfiguration, HibernateJpaAutoConfiguration)
# Enable JPA repositories.
  data:
    jpa:
      repositories:
        enabled: true
  jpa:
    database: MYSQL
# Initialize the schema on startup.
    generate-ddl: false
# DDL mode. This is actually a shortcut for the "hibernate.hbm2ddl.auto" property. Default to "create-drop" when using an embedded database, "none" otherwise.
    hibernate:
        ddl-auto: none
        open-in-view: false
# Additional native properties to set on the JPA provider.
    properties:
      hibernate:
        dialect :  org.hibernate.dialect.MySQL5Dialect
        format_sql: true
    show-sql: true

  redis:
    host: 192.168.111.147
    port: 6379
    database: 3
    timeout: 20000ms
    password:
    jedis:
      pool:
        max-active: 8
        min-idle: 0
        max-idle: 8
        max-wait: -1ms
    cache:
      time: 3000
      enable: true

conf:
  address:
    smp: http://192.168.11.130:8026

ftp:
   host: 192.168.10.25
   port: 21
   username: uftp
   password: 1234
   ftpPath: /data/
   visit:  http://192.168.10.25:8050/
   imageSize: 10485760

猜你喜欢

转载自www.cnblogs.com/guanxiaohe/p/11949463.html