This article refers to network, assault and deletion

This series of articles will be organized into my GitHub repository for the Java Interview Guide. Check out my repository for more highlights

https://github.com/h2pl/Java-Tutorial

If you like, please click Star

The article was first posted on my personal blog:

www.how2playlife.com

This series of posts will tell you what is a distributed system, it is very important for the back-end engineer a business, we will gradually learn common distributed technology, and some of the more common distributed system concept, but also need to further understand the zookeeper, distributed transaction, distributed lock and load balancing technology, In order to give you a more complete understanding of the actual practice of distributed technology, ready for the real application of distributed technology.

If you have any suggestions or questions about this series of articles, you can also contact the author on the public account “Java Technology Jianghu”. You are welcome to participate in the creation and revision of this series of blog posts.

This article is reprinted from linkedkeeper.com

Once you are familiar with Spring Boot, it is very easy to integrate an external extension. It is also very simple to integrate Redis. See the following steps for configuration:

Add POM dependencies

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-redis</artifactId>
        </dependency>Copy the code

Redisclient.java (); redisClient.java ()

    package org.springframework.data.redis.connection.jedis;Copy the code
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.UnsupportedEncodingException;Copy the code
    import org.apache.commons.lang3.StringUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;Copy the code
    import redis.clients.jedis.Jedis;
    import redis.clients.jedis.Protocol;
    import redis.clients.jedis.exceptions.JedisException;Copy the code
FetchJedisConnector (); /** * RedisClient; /** RedisClient So this class needs to be in the same package as JedisConnectionFactory * * @author (CSDN CATOOP) * @create April 9, 2017 */ public class RedisClient {Copy the code
        private static Logger logger = LoggerFactory.getLogger(RedisClient.class);Copy the code
        private JedisConnectionFactory factory;Copy the code
        public RedisClient(JedisConnectionFactory factory) {
            super();
            this.factory = factory;
        }Copy the code
/** * public void putObject(final String key, final Object value, final int cacheSeconds) { if (StringUtils.isNotBlank(key)) { redisTemplete(key, new RedisExecute<Object>() { @Override public Object doInvoker(Jedis jedis) { try { jedis.setex(key.getBytes(Protocol.CHARSET), cacheSeconds, serialize(value)); } catch (UnsupportedEncodingException e) { }Copy the code
return null; }}); }}Copy the code
/** * public Object getObject(final String key) {return redisTemplete(key, new RedisExecute<Object>() { @Override public Object doInvoker(Jedis jedis) { try { byte[] byteKey = key.getBytes(Protocol.CHARSET); byte[] byteValue = jedis.get(byteKey); if (byteValue ! = null) { return deserialize(byteValue); } } catch (UnsupportedEncodingException e) { return null; } return null; }}); }Copy the code
/** * setex operation ** @param key * @param Value * Value * @Param cacheSeconds * Timeout, Public String set(final String key, final String value, final int cacheSeconds) { return redisTemplete(key, new RedisExecute<String>() { @Override public String doInvoker(Jedis jedis) { if (cacheSeconds == 0) { return jedis.set(key, value); } return jedis.setex(key, cacheSeconds, value); }}); }Copy the code
/** * public String get(final String key) {return redisTemplete(key, new RedisExecute<String>() { @Override public String doInvoker(Jedis jedis) { String value = jedis.get(key); return StringUtils.isNotBlank(value) && !" nil".equalsIgnoreCase(value) ? value : null; }}); }Copy the code
/** * public long del(final String key) {return redisTemplete(key, new RedisExecute<Long>() { @Override public Long doInvoker(Jedis jedis) { return jedis.del(key); }}); }Copy the code
/** * obtain resources ** @return * @throws JedisException */ public Jedis getResource() throws JedisException {Jedis Jedis = null; try { jedis = factory.fetchJedisConnector(); } catch (JedisException e) { logger.error("getResource.", e); returnBrokenResource(jedis); throw e; } return jedis; }Copy the code
/** * get resources ** @return * @throws JedisException */ public Jedis getJedis() throws JedisException {return getResource();  }Copy the code
@param jedis @param isBroken public void returnBrokenResource(jedis jedis) {if (jedis! = null) { jedis.close(); }}Copy the code
@param jedis @param isBroken */ public void returnResource(jedis jedis) {if (jedis! = null) { jedis.close(); }}Copy the code
** @param key * @param execute * @return */ public <R> R redisTemplete RedisExecute<R> execute) { Jedis jedis = null; try { jedis = getResource(); if (jedis == null) { return null; }Copy the code
                return execute.doInvoker(jedis);
            } catch (Exception e) {
                logger.error("operator redis api fail,{}", key, e);
            } finally {
                returnResource(jedis);
            }
            return null;
        }Copy the code
/** * * * @param source * entity to be converted * @return Converted byte array * @throws Exception */ public static byte[] serialize(Object source) { ByteArrayOutputStream byteOut = null; ObjectOutputStream ObjOut = null; try { byteOut = new ByteArrayOutputStream(); ObjOut = new ObjectOutputStream(byteOut); ObjOut.writeObject(source); ObjOut.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (null ! = ObjOut) { ObjOut.close(); } } catch (IOException e) { ObjOut = null; } } return byteOut.toByteArray(); }Copy the code
/** * Deserialize byte array into entity Bean. * * @param source * Byte array to be deserialized * @return Deserialized entity Bean * @throws Exception */ public static Object deserialize(byte[] source) { ObjectInputStream ObjIn = null; Object retVal = null; try { ByteArrayInputStream byteIn = new ByteArrayInputStream(source); ObjIn = new ObjectInputStream(byteIn); retVal = ObjIn.readObject(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (null ! = ObjIn) { ObjIn.close(); } } catch (IOException e) { ObjIn = null; } } return retVal; }Copy the code
interface RedisExecute<T> { T doInvoker(Jedis jedis); }}Copy the code

Create Redis config class redisconfig.java

    package com.shanhy.example.redis;Copy the code
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
    import org.springframework.data.redis.connection.jedis.RedisClient;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.serializer.StringRedisSerializer;Copy the code
/** * @author * @create 2016年9月12日 */ @configuration public class RedisConfig {Copy the code
        @Bean
        public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory factory) {
            RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
            template.setConnectionFactory(factory);
            template.setKeySerializer(new StringRedisSerializer());
            template.setValueSerializer(new RedisObjectSerializer());
            template.afterPropertiesSet();
            return template;
        }Copy the code
@Bean public RedisClient redisClient(JedisConnectionFactory factory){ return new RedisClient(factory); }}Copy the code
    RedisObjectSerializer.javaCopy the code
    package com.shanhy.example.redis;Copy the code
    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;Copy the code
/ achieve object serialization interface * * * * @ author ChanHongYu (365384722) * * @ @ myblog http://blog.csdn.net/catoop/ create on April 9, 2017 * / public class RedisObjectSerializer implements RedisSerializer<Object> {Copy the code
        private Converter<Object, byte[]> serializer = new SerializingConverter();
        private Converter<byte[], Object> deserializer = new DeserializingConverter();Copy the code
        static final byte[] EMPTY_ARRAY = new byte[0];Copy the code
        @Override
        public Object deserialize(byte[] bytes) {
            if (isEmpty(bytes)) {
                return null;
            }Copy the code
try { return deserializer.convert(bytes); } catch (Exception ex) { throw new SerializationException("Cannot deserialize", ex); }}Copy the code
        @Override
        public byte[] serialize(Object object) {
            if (object == null) {
                return EMPTY_ARRAY;
            }Copy the code
try { return serializer.convert(object); } catch (Exception ex) { return EMPTY_ARRAY; }}Copy the code
        private boolean isEmpty(byte[] data) {
            return (data == null || data.length == 0);
        }Copy the code
    }Copy the code

Put the following code in any Controller

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;Copy the code
@requestMapping ("/redisTest") public String redisTest() {the try {redisTemplate. OpsForValue (). The set (" test - key ", "redis test content", 2, TimeUnit. SECONDS); // The cache validity period is 2 secondsCopy the code
Logger. The info (" read data from the Redis: "+ redisTemplate. OpsForValue () get (" test - key"). The toString ());Copy the code
            TimeUnit.SECONDS.sleep(3);Copy the code
Logger. The info (" wait for 3 seconds, then try to read the data: "+ redisTemplate. OpsForValue () get (" test - key")); } catch (InterruptedException e) { e.printStackTrace(); }Copy the code
        return "OK";
    }Copy the code

Redisapplication.yml

Redis: host: 192.168.1.101 port: 6379 password: # Connection timeout timeout: 10000 Pool: max-idle: 20 min-idle: 5 max-active: 20 max-wait: 2Copy the code

This completes the Redis configuration and is ready to use the redisTemplate normally.

atoop/article/details/71275331

1. Create a Caching configuration class

RedisKeys.java

package com.shanhy.example.redis; import java.util.HashMap; import java.util.Map; import javax.annotation.PostConstruct; import org.springframework.stereotype.Component; ** @author SHANHY */ @Component public class RedisKeys {begin public static final String _CACHE_TEST = "_cache_test"; Public static final Long _CACHE_TEST_SECOND = 20L; Private Map<String, Long> expiresMap = null; private Map<String, Long> expiresMap = null; @PostConstruct public void init(){ expiresMap = new HashMap<>(); expiresMap.put(_CACHE_TEST, _CACHE_TEST_SECOND); } public Map<String, Long> getExpiresMap(){ return this.expiresMap; }}Copy the code

CachingConfig.java

package com.shanhy.example.redis; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; 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.cache.interceptor.SimpleKeyGenerator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.core.RedisTemplate; /** * Annotation environment management ** @author CSDN Catoop * @create September 12, 2016 */ @Configuration @enablecaching Public Class CachingConfig extends CachingConfigurerSupport {/** * if you do not specify a key when using @cacheable, Then use a default key generator to generate a key * * @return * * @author (CSDN CATOOP) * @create March 11, 2017 */ @override public KeyGenerator KeyGenerator() {return new SimpleKeyGenerator() {MD5 */ @override public Object generate(Object target, Method method, Object... params) { StringBuilder sb = new StringBuilder(); sb.append(target.getClass().getName()); sb.append(".").append(method.getName()); StringBuilder paramsSb = new StringBuilder(); For (Object param: params) {// If not specified, the default generation is included in the key value if (param! = null) { paramsSb.append(param.toString()); } } if (paramsSb.length() > 0) { sb.append("_").append(paramsSb); } return sb.toString(); }}; } /** * Manage cache ** @param redisTemplate * @return */ @bean public CacheManager CacheManager (redisTemplate <String, Object> redisTemplate, RedisKeys redisKeys) { RedisCacheManager rcm = new RedisCacheManager(redisTemplate); // Set the default cache expiration time (global) rcm.setDefaultExpiration(1800); Rcm.setexpires (rediskeys.getExpiresMap ()); List<String> cacheNames = new ArrayList<String>(redisKeys.getExpiresMap().keySet()); rcm.setCacheNames(cacheNames); return rcm; }}Copy the code

Create a class that needs to cache data

TestService.java

package com.shanhy.example.service; import org.apache.commons.lang3.RandomStringUtils; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import com.shanhy.example.redis.RedisKeys; @service public class TestService {/** * fixed key ** @return * @author SHANHY * @create April 9, 2017 */ @cacheable (value = RedisKeys._CACHE_TEST, key = "'" + RedisKeys._CACHE_TEST + "'") public String testCache() { return RandomStringUtils.randomNumeric(4); } /** * The key stored in Redis is automatically generated, Generate rules. See CachingConfig keyGenerator () method * * @ param str1 * * @ @ param str2 return * @ author SHANHY * @ the create on April 9, 2017 * / @Cacheable(value = RedisKeys._CACHE_TEST) public String testCache2(String str1, String str2) { return RandomStringUtils.randomNumeric(4); }}Copy the code

To clarify, the value in @cacheable is configured in the cacheManager of CachingConfig to configure our cache lifetime. MethodKeyGenerator is the KeyGenerator declared in CachingConfig. There are several other cache-related annotations that you can read about, but the one we use is @cacheable, which generally works for most of our needs. We can also configure @cacheable expressions to determine whether we need caching based on the parameter values we pass. Mapper. get = mapper.get = mapper.get = mapper.get = mapper.get = mapper.get = mapper.get = mapper.get = mapper.get = mapper.get = mapper.get = mapper.get = mapper.get = mapper.get = mapper.get = mapper.get = mapper.get

Three, test method

I’m going to put this code in any Controller

package com.shanhy.example.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.connection.jedis.RedisClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.shanhy.example.service.TestService; Test Controller / * * * * * @ author ChanHongYu (365384722) * * @ @ myblog http://blog.csdn.net/catoop/ create on April 9, 2017 * / @RestController @RequestMapping("/test") public class TestController { private static final Logger LOG = LoggerFactory.getLogger(TestController.class); @Autowired private RedisClient redisClient; @Autowired private TestService testService; @GetMapping("/redisCache") public String redisCache() { redisClient.set("shanhy", "hello,shanhy", 100); LOG.info("getRedisValue = {}", redisClient.get("shanhy")); testService.testCache2("aaa", "bbb"); return testService.testCache(); }}Copy the code

So far!

Finally, @cacheable can be used on almost any method, including Controller methods (I didn’t test this).