原创

Spring Boot(五)集成 Redis


项目GitHub地址 :

https://github.com/FrameReserve/TrainingBoot


Spring Boot(五)集成 Redis ,标记地址:

https://github.com/FrameReserve/TrainingBoot/releases/tag/0.0.5


Centos7 安装 Redis 3.2.0

http://blog.csdn.net/a286352250/article/details/51603189


Centos7 开机启动 Redis 3.2.0

http://blog.csdn.net/a286352250/article/details/52595387



pom.xml

完整配置请看GitHub。

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

Spring Boot配置文件:

src/main/resources/application.yml

spring:
    
    redis:
        database: 0
        host: 192.168.2.66
        password: foobared
        port: 6379
        pool:
            max-idle: 8
            min-idle: 0
            max-active: 10
            max-wait: -1
            

            


Redis 配置类:

src/main/java/com/training/core/redis/RedisConfig.java

package com.training.core.redis;

import java.io.Serializable;
import java.lang.reflect.Method;

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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

	@Bean
    public KeyGenerator biliKeyGenerator(){
        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(@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
        return new RedisCacheManager(redisTemplate);
    }

    @Bean
    public RedisTemplate<Serializable, Serializable> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
    	RedisTemplate<Serializable, Serializable> redisTemplate = new RedisTemplate<Serializable, Serializable>();
    	redisTemplate.setConnectionFactory(redisConnectionFactory);
        return redisTemplate;
    }
    
}


自定义Redis对象序列化工具类:RedisObjectSerializer

src/main/java/com/training/core/redis/RedisObjectSerializer.java

package com.training.core.redis;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.serializer.support.DeserializingConverter;
import org.springframework.core.serializer.support.SerializingConverter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

public class RedisObjectSerializer implements RedisSerializer<Object> {

  private Converter<Object, byte[]> serializer = new SerializingConverter();
  private Converter<byte[], Object> deserializer = new DeserializingConverter();

  static final byte[] EMPTY_ARRAY = new byte[0];

  public Object deserialize(byte[] bytes) {
    if (isEmpty(bytes)) {
      return null;
    }

    try {
      return deserializer.convert(bytes);
    } catch (Exception ex) {
      throw new SerializationException("Cannot deserialize", ex);
    }
  }

  public byte[] serialize(Object object) {
    if (object == null) {
      return EMPTY_ARRAY;
    }

    try {
      return serializer.convert(object);
    } catch (Exception ex) {
      return EMPTY_ARRAY;
    }
  }

  private boolean isEmpty(byte[] data) {
    return (data == null || data.length == 0);
  }
}


定义Redis BaseDaoImpl,统一增删改查:

src/main/java/com/training/core/dao/impl/RedisBaseDaoImpl.java

package com.training.core.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;

import com.google.gson.Gson;
import com.training.core.dao.BaseDao;
import com.training.core.dto.FlexiPageDto;
import com.training.core.entity.BaseEntity;

import org.springframework.stereotype.Repository;

import tk.mybatis.mapper.entity.Example;

@Repository("redisBaseDao")
public class RedisBaseDaoImpl<T extends BaseEntity> implements BaseDao<T> {

	@Autowired
    protected RedisTemplate<Serializable, Serializable> redisTemplate;

	@Override
	public T getEntityById(final Class<T> cls, final Integer id) {
		return redisTemplate.execute(new RedisCallback<T>() {
            @Override
            public T doInRedis(RedisConnection connection) throws DataAccessException {
                byte[] key = redisTemplate.getStringSerializer().serialize(cls.getName() + "_" + id);
                if (connection.exists(key)) {
                    byte[] value = connection.get(key);
                    String json = redisTemplate.getStringSerializer().deserialize(value);
                    return new Gson().fromJson(json, cls);
                }
                return null;
            }
        });
	}
	
    public void addEntity(final T entity) {
        redisTemplate.execute(new RedisCallback<Object>() {

            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                connection.set(redisTemplate.getStringSerializer().serialize(entity.getClass().getName() + "_" + entity.getId()),
                               redisTemplate.getStringSerializer().serialize(new Gson().toJson(entity)));
                return null;
            }
        });
    }

	@Override
	public void updateEntity(final T entity) {
		redisTemplate.execute(new RedisCallback<Object>() {

            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                connection.set(redisTemplate.getStringSerializer().serialize(entity.getClass().getName() + "_" + entity.getId()),
                               redisTemplate.getStringSerializer().serialize(new Gson().toJson(entity)));
                return null;
            }
        });
	}

	@Override
	public void deleteEntityById(final Class<T> cls, final Integer id) {
		redisTemplate.execute(new RedisCallback<Object>() {

            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                connection.del(redisTemplate.getStringSerializer().serialize(cls.getName() + "_" + id.toString()));
                return null;
            }
        });
	}

    public void setRedisTemplate(RedisTemplate<Serializable, Serializable> redisTemplate) {
		this.redisTemplate = redisTemplate;
	}
    
}
















正文到此结束
Loading...