In the actual development, caching is a must. It is impossible that every time the client requests the server, the server has to go to the database for search every time. Why use caching? It’s all about improving the speed of the system. The user frequently accessed content stored in the nearest to the user, the fastest access to the place, improve the user response speed, today first to tell the next redis integration in Springboot detailed steps.

A, install,

First, you need to install a redis program locally, redis download address, the installation process is very simple (skipped), after the installation is completed into the redis folder can be seen as follows:

Click Redis-server. exe to start the Redis service, and it can be seen as the following picture, which means that the Redis service is successfully started:

Two, integration into SpringBoot

Add the redis dependency to the project. Add the following to the POM file:

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

Add redis configuration to application.yml

The default password is emptyRedis: host: 127.0.0.1# Redis server connection port
      port: 6379
      jedis:
        pool:
          # maximum number of connections in the pool (use negative values to indicate no limit)
          max-active: 100
          Minimum free connection in connection pool
          max-idle: 10
          Maximum connection pool blocking wait time (negative value indicates no limit)
          max-wait: 100000
      Connection timeout (ms)
      timeout: 5000
      The default is a database with index 0
      database: 0 
Copy the code

3. Create the RedisConfiguration class, inherit CachingConfigurerSupport, and enable the annotation @enablecaching

@Configuration@enablecaching Public class RedisConfiguration extends CachingConfigurerSupport {/** * Specifies a custom key generation rule */ @Override public KeyGeneratorkeyGenerator() {
        return new KeyGenerator() { @Override public Object generate(Object o, Method method, Object... StringBuilder sb = new StringBuilder(); Sb.append (o.getClass().getName()); // Append the method name sb.append(method.getName()); // Iterate over the parameters and appendfor (Object obj : objects) {
                    sb.append(obj.toString());
                }
                System.out.println(Call Redis cache Key: + sb.toString());
                returnsb.toString(); }}; } /** * use RedisCacheManager as the CacheManager * @param connectionFactory */ @bean public CacheManager cacheManager(RedisConnectionFactory connectionFactory) { RedisCacheManager redisCacheManager = RedisCacheManager.create(connectionFactory);returnredisCacheManager; } @Bean public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {//// redisTemplate template = new StringRedisTemplate(factory); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); template.setValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet();returntemplate; }}Copy the code

4. Create a custom interface to define the required redis functionality

/** * K refers tohashStructure operation key type * T for data entity should implement serialization interface, and define serialVersionUID * RedisTemplate provides five data structure operation typeshash / list / set/ zset/value * The method is named in the format of data operation type + operation as followshashPut refers tohashPublic interface RedisHelper<HK, T> {/** * Hash structure to add elements * @param key key * @paramhashKey hashKey * @param domain element */ voidhashPut(String key, HK hashKey, T domain); /** * the Hash structure retrieves all key-value pairs * @param key * @ for the specified keyreturn
     */
    Map<HK, T> hashFindAll(String key); /** * The Hash structure gets a single element * @param key * @paramhashKey * @return
     */
    T hashGet(String key, HK hashKey);

    void hashRemove(String key, HK hashKey); /** * List adds element * @param key * @param domain * @ to the end (Right)return*/ Long listPush(String key, T domain); /** * List adds elements to the header (Left) * @param key * @param domain * @return*/ Long listUnshift(String key, T domain); /** * List gets all elements * @param key * @return*/ List<T> listFindAll(String key); /** * List removes and retrieves the first element of the array * @param key * @return*/ T listLPop(String key); /** * Object entity class * @param key * @param domain * @return*/ void valuePut(String key, T domain); /** * get the object entity class * @param key * @return*/ T getValue(String key); void remove(String key); /** * set expiration time * @param key * @param timeUnit timeUnit */ Boolean expirse(String key, long timeout, TimeUnit timeUnit); }Copy the code

The next step is to create a RedisHelperImpl to implement the interface

@Service("RedisHelper") public class RedisHelperImpl<HK, T> implements RedisHelper<HK, T> {//hashPrivate RedisTemplate<String, T> RedisTemplate; // Instantiate the operation object in the constructor via the factory method of redisTemplate private HashOperations<String, HK, T>hashOperations;
    private ListOperations<String, T> listOperations;
    private ZSetOperations<String, T> zSetOperations;
    private SetOperations<String, T> setOperations; private ValueOperations<String, T> valueOperations; @autoWired public RedisHelperImpl(RedisTemplate<String, T> redisTemplate) { this.redisTemplate = redisTemplate; this.hashOperations = redisTemplate.opsForHash(); this.listOperations = redisTemplate.opsForList(); this.zSetOperations = redisTemplate.opsForZSet(); this.setOperations = redisTemplate.opsForSet(); this.valueOperations = redisTemplate.opsForValue(); } @Override public voidhashPut(String key, HK hashKey, T domain) {
        hashOperations.put(key, hashKey, domain);
    }

    @Override
    public Map<HK, T> hashFindAll(String key) {
        return hashOperations.entries(key);
    }

    @Override
    public T hashGet(String key, HK hashKey) {
        return hashOperations.get(key, hashKey);
    }

    @Override
    public void hashRemove(String key, HK hashKey) {
        hashOperations.delete(key, hashKey);
    }

    @Override
    public Long listPush(String key, T domain) {
        return listOperations.rightPush(key, domain);
    }

    @Override
    public Long listUnshift(String key, T domain) {
        return listOperations.leftPush(key, domain);
    }

    @Override
    public List<T> listFindAll(String key) {
        if(! redisTemplate.hasKey(key)) {return null;
        }
        return listOperations.range(key, 0, listOperations.size(key));
    }

    @Override
    public T listLPop(String key) {
        return listOperations.leftPop(key);
    }

    @Override
    public void valuePut(String key, T domain) {
        valueOperations.set(key, domain);
    }

    @Override
    public T getValue(String key) {
        return valueOperations.get(key);
    }

    @Override
    public void remove(String key) {
        redisTemplate.delete(key);
    }

    @Override
    public boolean expirse(String key, long timeout, TimeUnit timeUnit) {
        returnredisTemplate.expire(key, timeout, timeUnit); }}Copy the code

Three, test,

Write the TestRedis class to test it

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestRedis {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedisHelperImpl redisHelper;

    @Test
    public void testBasic writing () throws the Exception {/ / / / stringRedisTemplate opsForValue () set ("aaa"."111");
//        Assert.assertEquals("111",stringRedisTemplate.opsForValue().get("aaa"));
//        System.out.println(stringRedisTemplate.opsForValue().get("aaa"));
        Author user=new Author();
        user.setName("Alex");
        user.setIntro_l("A program that can't play basketball is not a good man.");
        redisHelper.valuePut("aaa",user);
        System.out.println(redisHelper.getValue("aaa"));
    }

    @Test
    public void testObj() throws Exception {
        Author user=new Author();
        user.setName("Jerry");
        user.setIntro_l("A program that can't play basketball is not a good man!");

        ValueOperations<String, Author> operations=redisTemplate.opsForValue();
        operations.set("502", user);
        Thread.sleep(500);
        boolean exists=redisTemplate.hasKey("502");
        if(exists){
            System.out.println(redisTemplate.opsForValue().get("502"));
        }else{
            System.out.println("exists is false");
        }
        // Assert.assertEquals("aa", operations.get("com.neo.f").getUserName()); }}Copy the code

Running the TestRedis test class results in the following:

Note: If RedisConfiguration is not configured with the redisTemplate(RedisConnectionFactory Factory) annotation, there will be a serialization problem for keys and values. If you are interested, try it.

Iv. Actual combat of the project

The annotation @enablecaching is added to the entry of the Application to EnableCaching

@enablecaching @springBootApplication public class PoetryApplication {public static void main(String[] args) { SpringApplication.run(PoetryApplication.class, args); }}Copy the code

The above redis related notation is our custom Settings and obtain, so we often need to access the interface to use Redis to cache related entity objects and collections, so how do we implement? What if I want to cache author information in AuthorController? As follows:

@RestController
@RequestMapping(value = "/poem")
public class AuthorController {

    private final static Logger logger = LoggerFactory.getLogger(AuthorController.class);

    @Autowired
    private AuthorRepository authorRepository;

    @Cacheable(value="poemInfo") // Automatically generate cache by method @postmapping (value ="/poemInfo")
    public Result<Author> author(@RequestParam("author_id") int author_id, @RequestParam("author_name")String author_name) {
        if(StringUtils.isEmpty(author_id) || StringUtils.isEmpty(author_name)){
            return ResultUtils.error(ResultCode.INVALID_PARAM_EMPTY);
        }
        Author author;
        Optional<Author> optional = authorRepository.getAuthorByIdAndName(author_id, author_name);
        if(optional.isPresent()) { author = optional.get(); // Filter by \n or more Spacesif(! StringUtils.isEmpty(author.getIntro_l())) { String s = author.getIntro_l(); String intro = s.split("\\s +")[0];
                author.setIntro_l(intro);
            }
        } else {
           return ResultUtils.error(ResultCode.NO_FIND_THINGS);
        }
        returnResultUtils.ok(author); }}Copy the code

The @cacheable (value=”poemInfo”) annotation means that the cache is automatically generated based on the method, and value is the cached key.

So far we have integrated Redis into SpringBoot. If you are interested, you can pay attention to our open source Android App “The Most Beautiful Poems”.

App “Most Beautiful Poetry” Android side source code Github address: VinsonGuo/ Android-poetry

App “the most beautiful Poetry” server-side source (this tutorial)Github address: Alei-Jerry/Java-poetry

App “the most beautiful poetry” APK cool Ann download address: the most beautiful poetry (com.tech502.poetry) – 1.0 – application – cool Ann website