• Redis在springboot项目的使用


    一、在pom.xml配置redis依赖

    <!-- redis客户端代码 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <!-- json工具 -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.49</version>
    </dependency>
    <!-- redis需要用到这个依赖,否则报错 -->
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-pool2</artifactId>
    </dependency>
    

    二、在common包中自定义一个RedisService以及其实现类

    Redis的方法比较复杂,可以将经常使用的抽取成方法,形成工具类,方便调用(使用接口加实现类的方式);调用redis时,如下

    @Autowired
    private RedisService redisService;

    RedisService.java接口

    package cn.kooun.common.redis;
    
    import cn.kooun.common.redis.entity.MessageCommon;
    
    /**
     * redis service
     */
    public interface RedisService {
    	/**
    	 * 添加
    	 * 
    	 * @param key
    	 * @param value
    	 * @return
    	 */
    	boolean set(final String key, Object value);
    	/**
    	 * 添加 有生命周期
    	 * 
    	 * @param key
    	 * @param value
    	 * @param expireTime
    	 * @return
    	 */
    	boolean set(final String key, Object value, Long expireTime);
    	/**
    	 * 获取
    	 * 
    	 * @param key
    	 * @return
    	 */
    	Object get(String key);
    	/**
    	 * 删除
    	 * 
    	 * @param key
    	 */
    	void delete(final String key);
    	/**
    	 * 	发送广播消息
    	 * @param topic
    	 * @param body
    	 */
    	void sendTopic(String topic, MessageCommon body);
    }
    

    实现类RedisServiceImpl.java

    package cn.kooun.common.redis.impl;
    
    import java.util.concurrent.TimeUnit;
    
    import javax.annotation.Resource;
    
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.core.ValueOperations;
    import org.springframework.stereotype.Service;
    
    import com.alibaba.fastjson.JSON;
    
    import cn.kooun.common.redis.RedisService;
    import cn.kooun.common.redis.entity.MessageCommon;
    
    /**
     * redis工具类
     */
    @Service
    public class RedisServiceImpl implements RedisService{
    	@Resource
        private RedisTemplate<String, Object> redisTemplate;
    	
    	/**
    	 * 添加
    	 * 
    	 * @param key
    	 * @param value
    	 * @return
    	 */
    	@SuppressWarnings("all")
    	@Override
        public boolean set(final String key, Object value) {
            boolean result = false;
        	ValueOperations<String, Object> operations = redisTemplate.opsForValue();
        	operations.set(key, value);
        	return true;
        }
    	/**
    	 * 添加带生命周期
    	 */
    	@Override
        public boolean set(final String key, Object value, Long expireTime) {
            boolean result = false;
            ValueOperations<String, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value, expireTime, TimeUnit.SECONDS);
            result = true;
            return result;
        }
    	/**
    	 * 获取
    	 */
    	@Override
    	public Object get(final String key) {
    		ValueOperations<String, Object> operations = redisTemplate.opsForValue();
    		return operations.get(key);
    	}
    	/**
    	 * 删除
    	 */
    	@Override
    	@SuppressWarnings("all")
        public void delete(final String key) {
    		redisTemplate.delete(key);
        }
    	
    	/**
    	 * 	发送广播消息
    	 */
    	@Override
    	public void sendTopic(String topic,MessageCommon body) {
    		body.setConsumerTopic(topic);
    		redisTemplate.convertAndSend(topic,JSON.toJSONString(body));
    	}
    }
    

    redis广播消息体实体类MessageCommon

    package cn.kooun.common.redis.entity;
    
    /**
     *  redis广播消息体实体类
     * @author chenWei
     * @date 2019年11月7日 上午10:47:08
     */
    public class MessageCommon {
    	/**对方监听器执行回调的方法名*/
    	private String method;
    	/**消息体*/
    	private String body;
    	/**消息生产者的消费主题,便于回复消息*/
    	private String producerTopic;
    	/**消费者消费的主题*/
    	private String consumerTopic;
    	
    	public MessageCommon(String method, String body) {
    		this.method = method;
    		this.body = body;
    	}
    	
    	public String getMethod() {
    		return method;
    	}
    	public void setMethod(String method) {
    		this.method = method;
    	}
    	public String getBody() {
    		return body;
    	}
    	public void setBody(String body) {
    		this.body = body;
    	}
    
    	public String getProducerTopic() {
    		return producerTopic;
    	}
    
    	public void setProducerTopic(String producerTopic) {
    		this.producerTopic = producerTopic;
    	}
    
    	public String getConsumerTopic() {
    		return consumerTopic;
    	}
    
    	public void setConsumerTopic(String consumerTopic) {
    		this.consumerTopic = consumerTopic;
    	}
    
    	@Override
    	public String toString() {
    		return "MessageCommon [method=" + method + ", body=" + body + ", producerTopic=" + producerTopic
    				+ ", consumerTopic=" + consumerTopic + "]";
    	}
    	
    }
    

    三、redis可视化工具乱码(springboot中添加一个类)

    package cn.kooun.common.redis;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.redis.connection.RedisConnectionFactory;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
    import org.springframework.data.redis.serializer.StringRedisSerializer;
    
    /**
     * 	解决redis可视化工具乱码问题
     * @author HuangJingNa
     * @date 2019年12月21日 下午3:15:19
     *
     */
    @Configuration
    public class RedisConfigBean {
    
        /**
         * redis 防止key value 前缀乱码.
         *
         * @param factory redis连接 factory
         * @return redisTemplate
         */
        @Bean(name = "redisTemplate")
        public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
            RedisTemplate<String, Object> template = new RedisTemplate<>();
            template.setConnectionFactory(factory);
            template.setKeySerializer(new StringRedisSerializer());
            template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
            template.setHashKeySerializer(new GenericJackson2JsonRedisSerializer());
            template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
            template.afterPropertiesSet();
            return template;
        }
    
    }
    

    package cn.kooun.core.config;
    
    import java.lang.reflect.Method;
    
    import org.springframework.beans.factory.annotation.Autowired;
    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.connection.RedisConnectionFactory;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
    import org.springframework.data.redis.serializer.StringRedisSerializer;
    
    import com.fasterxml.jackson.annotation.JsonAutoDetect;
    import com.fasterxml.jackson.annotation.PropertyAccessor;
    import com.fasterxml.jackson.databind.ObjectMapper;
    /**
     * redis配置
     * 
     * @author chenWei
     * @date 2019年9月12日 上午11:00:27
     *
     */
    @Configuration
    @EnableCaching
    //自动注入自定义对象到参数列表
    @SuppressWarnings("all")
    public class RedisConfig  extends CachingConfigurerSupport {
    	
    	/**
    	 * key的生成策略
    	 */
    	@Bean
        public KeyGenerator keyGenerator() {
            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;
                }
    
            };
        }
        /**
         * RedisTemplate配置
         * @author chenwei
         * @date 2019年7月2日 上午10:31:44
         * @param factory
         * @return
         */
        @Bean
        public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        	RedisTemplate<String, Object> template = new RedisTemplate<>();
            // 配置连接工厂
            template.setConnectionFactory(factory);
    
            //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
            Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);
    
            ObjectMapper om = new ObjectMapper();
            // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
            om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
            // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
            om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
            jacksonSeial.setObjectMapper(om);
    
            // 值采用json序列化
            template.setValueSerializer(jacksonSeial);
            //使用StringRedisSerializer来序列化和反序列化redis的key值
            template.setKeySerializer(new StringRedisSerializer());
    
            // 设置hash key 和value序列化模式
            template.setHashKeySerializer(new StringRedisSerializer());
            template.setHashValueSerializer(jacksonSeial);
            template.afterPropertiesSet();
    
            return template;
        }
        
        
    }
    
  • 相关阅读:
    java url 获取文件_[转]从URL获取文件保存到本地的JAVA代码,url 请求设置http请求头
    解决Mybatis中出现的Invalid bound statement (not found)问题
    使用多线程往LIST添加数据 线程安全list
    spring BeanUtils 工具实现对象之间的copy 属性复制,属性拷贝
    idea 打开Service窗口一个管理所有服务的地方
    java实现大文件下载(http方式)
    Java @Override注解写与不写的区别
    Linux下C++共享内存
    Linux配置开机自启
    Linux中zsh出现 zsh: corrupt history file /XXX/.zsh_history解决办法
  • 原文地址:https://www.cnblogs.com/nadou/p/14003652.html
Copyright © 2020-2023  润新知