Springboot2.0 xはredis lettuceを統合し、データキャッシュメカニズムを行う.多問題の統合(シングルマシンモード)

11731 ワード

統合ポリシーリファレンスhttps://blog.csdn.net/weixin_36586564/article/details/86002413
キャッシュポリシーリファレンスhttps://blog.csdn.net/zhangcongyi420/article/details/82686702
問題異常リファレンスhttps://blog.csdn.net/zhaoheng314/article/details/81564166
多方面のエッセンスに基づいてredisコードを統合すると以下のようになります.
  • プロファイル

  • # Redis     
    spring.redis.host=
    # Redis       (    )
    spring.redis.password=
    # Redis          6379
    spring.redis.port=
    #       (10  )
    spring.redis.timeout=
    # Redis      16   ,           ,   0  1 dev    
    spring.redis.database=
    #         (          )    8
    spring.redis.lettuce.pool.max-active=8
    #            (          )    -1
    spring.redis.lettuce.pool.max-wait=-1
    #                8
    spring.redis.lettuce.pool.max-idle=8
    #                0
    spring.redis.lettuce.pool.min-idle=0
  • 依存関係の構成

  • 
    
        org.springframework.boot
        spring-boot-starter-data-redis
    
    
    
        org.apache.commons
        commons-pool2
        2.5.0
    
    
    
        com.alibaba
        fastjson
        1.2.47
    
  • クラスの構成

  • import org.springframework.boot.autoconfigure.AutoConfigureAfter;
    import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
    import org.springframework.cache.CacheManager;
    import org.springframework.cache.annotation.EnableCaching;
    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.connection.lettuce.LettuceConnectionFactory;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.serializer.StringRedisSerializer;
    
    import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
    
    /**
     *    Template
     *             RedisTemplate,
     *           ,          ,             ,
     *            String          StringRedisTemplate   ,      …
     *
     * @author king
     * @since 2019/8/8
     */
    
    @EnableCaching
    @Configuration
    @AutoConfigureAfter(RedisAutoConfiguration.class)
    public class RedisCacheAutoConfiguration {
    
    	@SuppressWarnings("rawtypes")
    	@Bean
        public RedisTemplate redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) {
        	RedisTemplate template = new RedisTemplate<>();
        	 
            //  fastjson   
            FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer(Object.class);
            // key      StringRedisSerializer key      
            template.setKeySerializer(new StringRedisSerializer());
            template.setHashKeySerializer(new StringRedisSerializer());
            // value       fastJsonRedisSerializer
            template.setValueSerializer(fastJsonRedisSerializer);
            template.setHashValueSerializer(fastJsonRedisSerializer);
            
     
            template.setConnectionFactory(redisConnectionFactory);
            return template;
    
        }
        //     
        @Bean
        public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
            RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager
                    .RedisCacheManagerBuilder
                    .fromConnectionFactory(redisConnectionFactory);
            return builder.build();
        }
    }
  • ツールクラス

  • 
    import org.springframework.data.redis.core.*;
    import org.springframework.stereotype.Component;
    
    
    
    
    
    
    import java.util.List;
    import java.util.Set;
    import java.util.concurrent.TimeUnit;
    
    import javax.annotation.Resource;
    /**
     * redis    
     * @author kingxt
     * @date  2019 8 9 
     *
     */
    @Component
    public class RedisComponentUtils{
    
    	@Resource
        private RedisTemplate redisTemplate;
    
    
        /**
         *     
         * @param key
         * @param value
         * @return boolean
         */
        
        public boolean set(String key, Object value) {
            boolean result = false;
            redisTemplate.opsForValue().set(key, value);
    
            result = true;
            return result;
        }
    
        /**
         *           
         * @param key
         * @param value
         * @return boolean
         */
        
        public boolean set(String key, Object value, Long expireTime) {
            boolean result = false;
            ValueOperations operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            result = true;
            return result;
        }
    
        /**
         *        value
         * @param keys
         */
        
        public void remove(String... keys) {
            for (String key : keys) {
                remove(key);
            }
        }
    
        /**
         *     key
         * @param pattern
         */
        
        public void removePattern(String pattern) {
            Set keys = redisTemplate.keys(pattern);
            if (keys.size() > 0)
                redisTemplate.delete(keys);
        }
    
        /**
         *      value
         * @param key
         */
        
        public void remove(String key) {
            if (exists(key)) {
                redisTemplate.delete(key);
            }
        }
    
        /**
         *            value
         * @param key
         * @return
         */
        
        public boolean exists(String key) {
            return redisTemplate.hasKey(key);
        }
    
        /**
         *     
         * @param key
         * @return
         */
        
        public Object get(String key) {
            Object result = null;
            ValueOperations operations = redisTemplate.opsForValue();
            result = operations.get(key);
            return result;
        }
        /**
         *      
         * @param key
         * @param hashKey
         * @param value
         */
        
        public void hmSet(String key, Object hashKey, Object value){
            HashOperations hash = redisTemplate.opsForHash();
            hash.put(key,hashKey,value);
        }
    
        /**
         *       
         * @param key
         * @param hashKey
         * @return
         */
        
        public Object hmGet(String key, Object hashKey){
            HashOperations hash = redisTemplate.opsForHash();
            return hash.get(key,hashKey);
        }
    
        /**
         *     
         * @param k
         * @param v
         */
        
        public void lPush(String k,Object v){
            ListOperations list = redisTemplate.opsForList();
            list.rightPush(k,v);
        }
    
        /**
         *     
         * @param k
         * @param l
         * @param l1
         * @return
         */
        
        public List lRange(String k, long l, long l1){
            ListOperations list = redisTemplate.opsForList();
            return list.range(k,l,l1);
        }
    
        /**
         *     
         * @param key
         * @param value
         */
        
        public void setArray(String key,Object value){
            SetOperations set = redisTemplate.opsForSet();
            set.add(key,value);
        }
    
        /**
         *     
         * @param key
         * @return
         */
        
        public Set getArray(String key){
            SetOperations set = redisTemplate.opsForSet();
            return set.members(key);
        }
    
        /**
         *       
         * @param key
         * @param value
         * @param scoure
         */
        
        public void zAdd(String key,Object value,double scoure){
            ZSetOperations zset = redisTemplate.opsForZSet();
            zset.add(key,value,scoure);
        }
    
        /**
         *       
         * @param key
         * @param scoure
         * @param scoure1
         * @return
         */
        
        public Set rangeByScore(String key,double scoure,double scoure1){
            ZSetOperations zset = redisTemplate.opsForZSet();
            return zset.rangeByScore(key, scoure, scoure1);
        }
    
    }
  • キャッシュポリシー


  • キャッシュポリシーリファレンスhttps://blog.csdn.net/zhangcongyi420/article/details/82686702
    現在のビジネスロジックに影響を及ぼさない必要があると一般的に考えられています
    例えば削除、更新、新規データの場合はredisのkeyを削除すべき
    たとえば、キャッシュでクエリーがデータベースにクエリーされない場合は、キャッシュに格納します.
    一般的なデータには有効期限が設定されています

    1.テストケース


    Serializableを実装する必要があります
    
    
    import java.io.Serializable;
    
    
    
    public class User implements Serializable{
    	private static final long serialVersionUID = -1L;
        private Long id;
        private String username;
        private String password;
        
    	public User(Long id, String username, String password) {
    		this.id = id;
    		this.username = username;
    		this.password = password;
    	}
    	public Long getId() {
    		return id;
    	}
    	public void setId(Long id) {
    		this.id = id;
    	}
    	public String getUsername() {
    		return username;
    	}
    	public void setUsername(String username) {
    		this.username = username;
    	}
    	public String getPassword() {
    		return password;
    	}
    	public void setPassword(String password) {
    		this.password = password;
    	}
        
    }
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.data.redis.core.RedisTemplate;
    
    import org.springframework.test.context.junit4.SpringRunner;
    import com.az.ugc.utils.RedisComponentUtils;
    import com.az.ugc.utils.UGCDictUtils;
    
    
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.stream.IntStream;
    
    import javax.annotation.Resource;
    
    /**
     * @author king    
     * @since 20190808
     */
    @RunWith(SpringRunner.class)
    @SpringBootTest(classes=RedisTest.class)
    @SpringBootApplication
    public class RedisTest {
    
        private static final Logger log = LoggerFactory.getLogger(RedisTest.class);
    
    
        @Resource
        private RedisTemplate redisCacheTemplate;
        @Resource
    	private RedisComponentUtils redisService;
    
        @Test
        public void get() {
            // TODO       
            ExecutorService executorService = Executors.newFixedThreadPool(1000);
            IntStream.range(0, 1000).forEach(i ->
                    executorService.execute(() -> redisCacheTemplate.opsForValue().increment("kk", 1))
            );
            redisCacheTemplate.opsForValue().set("k1", "v1");
            final String k1 = (String) redisCacheTemplate.opsForValue().get("k1");
            log.info("[      ] - [{}]", k1);
            log.info("[    Null  ] - [{}]", redisCacheTemplate.opsForValue().get("k111"));
            
            // TODO        ,  Redis          ,Spring Data Redis          ,Redis         
            String key = UGCDictUtils.REDIS_ARTICLE_BANNER_CONDTION_KEY;
            redisCacheTemplate.opsForValue().set(key, new User(1L, "u1", "pa"));
            
            // TODO    String(   )
            log.info("    :{}",redisCacheTemplate.opsForValue().get(key));;
            User user = UGCDictUtils.convert(redisCacheTemplate.opsForValue().get(key).toString(), User.class) ;
            // User user = (User) redisCacheTemplate.opsForValue().get(key);       
            
            log.info("[      ] - [{}]", user);
            
            log.info("[    Null  ] - [{}]", redisCacheTemplate.opsForValue().get("13"));
            
            // service   
            log.info("service Info:{}",redisService.get("key").toString());
            
        }
    

    fastjsonを使っています