springboot整合redis

来源:互联网 发布:数据库sqlite怎么用 编辑:程序博客网 时间:2024/05/21 08:52

1、pom添加redis依赖

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

2、创建AppRedisConfig配置类

package com.caiwufei.springboot;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;import org.springframework.data.redis.connection.RedisConnectionFactory;import org.springframework.data.redis.core.HashOperations;import org.springframework.data.redis.core.ListOperations;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.core.SetOperations;import org.springframework.data.redis.core.ValueOperations;import org.springframework.data.redis.core.ZSetOperations;import org.springframework.data.redis.serializer.StringRedisSerializer;import com.caiwufei.entity.base.BaseEntity;public class AppRedisConfig {@Autowired    private RedisConnectionFactory redisConnectionFactory;        /**     *  实例化 RedisTemplate 对象     * @return     */    @Bean    public RedisTemplate<String, Object> functionDomainRedisTemplate() {        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();        initDomainRedisTemplate(redisTemplate, redisConnectionFactory);        return redisTemplate;    }        /**     * 设置数据存入 redis 的序列化方式     */    private void initDomainRedisTemplate(RedisTemplate<String, Object> redisTemplate, RedisConnectionFactory factory) {        redisTemplate.setKeySerializer(new StringRedisSerializer());        redisTemplate.setHashKeySerializer(new StringRedisSerializer());        redisTemplate.setHashValueSerializer(new BaseEntity<>());        redisTemplate.setValueSerializer(new BaseEntity<>());        redisTemplate.setConnectionFactory(factory);    }    /**     * 实例化 HashOperations 对象,可以使用 Hash 类型操作     */    @Bean    public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {        return redisTemplate.opsForHash();    }        /**     * 实例化 ValueOperations 对象,可以使用 String 操作     */    @Bean    public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {        return redisTemplate.opsForValue();    }        /**     * 实例化 ListOperations 对象,可以使用 List 操作     * @return     */    @Bean    public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {        return redisTemplate.opsForList();    }        /**     * 实例化 SetOperations 对象,可以使用 Set 操作     */    @Bean    public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {        return redisTemplate.opsForSet();    }        /**     * 实例化 ZSetOperations 对象,可以使用 ZSet 操作     */    @Bean    public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {        return redisTemplate.opsForZSet();    }}


3、创建RedisTemplate类,很多方法操作暂未添加。

package com.caiwufei.common.utils;import javax.annotation.PostConstruct;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.ValueOperations;import org.springframework.stereotype.Component;@Component("appRedisTemplate")public class RedisTemplate {private static RedisTemplate instance;@Autowiredprivate org.springframework.data.redis.core.RedisTemplate<String, Object> springRedisTemplate;@Autowiredprivate ValueOperations<String, Object> valueOperations;@PostConstructpublic void init() {instance = this;instance.springRedisTemplate = this.springRedisTemplate;instance.valueOperations = this.valueOperations;}public static Boolean hasKey(String key) {return instance.getSpringRedisTemplate().hasKey(key);}public static void delete(String key) {instance.getSpringRedisTemplate().delete(key);}public static void set(String key, Object value) {instance.getValueOperations().set(key, value);}public static Object get(String key) {return instance.getValueOperations().get(key);}public org.springframework.data.redis.core.RedisTemplate<String, Object> getSpringRedisTemplate() {return springRedisTemplate;}public void setSpringRedisTemplate(org.springframework.data.redis.core.RedisTemplate<String, Object> springRedisTemplate) {this.springRedisTemplate = springRedisTemplate;}public ValueOperations<String, Object> getValueOperations() {return valueOperations;}public void setValueOperations(ValueOperations<String, Object> valueOperations) {this.valueOperations = valueOperations;}}


package com.caiwufei.entity.base;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;import org.springframework.data.redis.serializer.RedisSerializer;import org.springframework.data.redis.serializer.SerializationException;public class BaseEntity<T> implements Serializable, RedisSerializer<T>{/** *  */private static final long serialVersionUID = 3812075907697557491L;@Overridepublic byte[] serialize(T t) throws SerializationException {if (t == null) {            return new byte[0];        }ObjectOutputStream oos = null;        ByteArrayOutputStream baos = null;        try {            // 序列化            baos = new ByteArrayOutputStream();            oos = new ObjectOutputStream(baos);            oos.writeObject(t);            byte[] bytes = baos.toByteArray();            return bytes;        } catch (Exception e) {            e.printStackTrace();        }        return null;}@SuppressWarnings("unchecked")@Overridepublic T deserialize(byte[] bytes) throws SerializationException {if (bytes == null || bytes.length == 0) {        return null;    }ByteArrayInputStream bais = null;    try {         // 反序列化         bais = new ByteArrayInputStream(bytes);         ObjectInputStream ois = new ObjectInputStream(bais);         return (T) ois.readObject();    } catch (Exception e) {         e.printStackTrace();    }    return null;}}



4、在main方法入口或者配置类上面引入redis配置类

@Import(AppRedisConfig.class)

5、在application.properties中添加redis的配置项目

#-------------------redis------------------------spring.redis.host=ipspring.redis.port=portspring.redis.password=****spring.redis.pool.max-active=10spring.redis.pool.max-wait=-1spring.redis.pool.max-idle=5spring.redis.pool.min-idle=0spring.redis.timeout=50spring.redis.ssl=false

6、使用

@RequestMapping("/redis")public Object testRedis(SSAccountInfo a) {SSAccountInfo bAccountInfo = ssAccountInfoService.getAccountById(a);RedisTemplate.set(bAccountInfo.getAccountId(), bAccountInfo);return RedisTemplate.get(bAccountInfo.getAccountId());}





原创粉丝点击