Spring Boot Road Primer (15) --- Spring Boot and Redis integration

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/Geffin/article/details/100123543

Redis is a memory-based model may be persistent log cache database, stored in the form of key-value format. This article will be to complete the integration with Redis Spring Boot by using RedisTemplate.

Introduction dependence

Code can not write, but have to rely guide, Spring Boot and integration needs Redis import the following dependencies:

		<!-- 集成Redis -->
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        
        <!--spring2.0集成redis所需common-pool2-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>
        
        <dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.8</version>
		</dependency>

2 Configuration application.properties

As follows application.properties our project:

# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接超时时间(毫秒)
spring.redis.timeout=10000

3 Open redis

Here Insert Picture Description
Into the root directory of the installation path Redis, enter the command redis-server.exe redis.windows.conf, the pattern appeared as follows, showing Redis ran successfully.

4 to write a controller

package edu.szu.test.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/redistest")
public class HelloController {

	@Autowired
    private RedisTemplate redisTemplate;

	@RequestMapping("/hello")
    public String hello(){
        redisTemplate.opsForValue().set("sub","com");
        return (String) redisTemplate.opsForValue().get("sub");
	}
}

Some small partners may be surprised, hey, you configure it? ! Why you can directly use Redis? But in fact, in Spring Boot, because the Spring Boot did almost all of the dirty work for us, we can directly use the Redis. Amazing, is not it?

redisTemplate.opsForValue().set("sub","com");
return (String) redisTemplate.opsForValue().get("sub");

Two lines of code in the meaning data into a redis then removed again redis this data and returns the front end. OK, now we run the startup class to see if the front will com show?

Enter your browser to http: // localhost: 8080 / redistest / hello
Here Insert Picture Description
nice! This means that we have the data stored in the redis and can be freely taken, that Redis integration with Spring Boot whether it is over? Nice try! In fact, we've forgotten an important step: serialization rules. If we do not redefine the serialization rules, the Redis client input key value is less than the query.

Do not believe? We can try, enter keys in Redis client *, see if we can query our Redis just inserted the key in the client?
Here Insert Picture Description

We have previously been emptied Redis cache, you can make sure that we just added to Redis key unique data to the client. You can see, we insert the key in fact, it has become a pile of garbage. In fact, this is the default serialization lead, although our program looks normal, but the client can not store our Redis key-value pairs inserted correctly.

Modifying sequence rules 5

A custom serialization generic classes:

package edu.szu.test.common;

import java.nio.charset.Charset;

import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

public class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
	 
    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
 
    private Class<T> clazz;
 
    public FastJsonRedisSerializer(Class<T> clazz) {
        super();
        this.clazz = clazz;
    }
 
    @Override
    public byte[] serialize(T t) throws SerializationException {
        if (null == t) {
            return new byte[0];
        }
        return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
    }
 
    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        if (null == bytes || bytes.length <= 0) {
            return null;
        }
        String str = new String(bytes, DEFAULT_CHARSET);
        return (T) JSON.parseObject(str, clazz);
    }
 
}

Then we realize a redis configuration class:

package edu.szu.test.common;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
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.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
public class RedisConfig {
 
    @Bean
    @ConditionalOnMissingBean(name = "redisTemplate")
    public RedisTemplate<Object, Object> redisTemplate(
            RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
 
        //使用fastjson序列化
        FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer(Object.class);
        // value值的序列化采用fastJsonRedisSerializer
        template.setValueSerializer(fastJsonRedisSerializer);
        template.setHashValueSerializer(fastJsonRedisSerializer);
        // key的序列化采用StringRedisSerializer
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
 
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
 
    @Bean
    @ConditionalOnMissingBean(StringRedisTemplate.class)
    public StringRedisTemplate stringRedisTemplate(
            RedisConnectionFactory redisConnectionFactory) {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
 
}

The code is written, we modify the key value and a sequence of rules, the sequence of the key itself provides Redis manner, serialization fastjson value with our custom.

Open classes start again, enter your browser to http: // localhost: 8080 / redistest / hello, see Redis client:
Here Insert Picture Description
add Redis key-value pairs in the program is correctly added to the Redis client, on behalf of Spring Boot and Redis has integration is completed.

6 Supplement: value non string object

Our example above is the case for the value of the string object, if the value is non-string object And how? In fact, essentially it is exactly the same as before, directly following the code.

We first establish a pojo

public class Person{
	
	private int num;
	private String str;
	
	@Override
	public String toString() {
		return "Person [num=" + num + ", str=" + str + "]";
	}
	
	public Person() {
		
	}
	
	public Person(int num,String str) {
		this.num = num;
		this.str = str;
	}

	public int getNum() {
		return num;
	}

	public void setNum(int num) {
		this.num = num;
	}

	public String getStr() {
		return str;
	}

	public void setStr(String str) {
		this.str = str;
	}
	
}

Note, be sure to add an empty constructor, otherwise it will complain! !

Then we changed a bit controllers

@RestController
@RequestMapping("/redistest")
public class HelloController {

	@Autowired
    private RedisTemplate redisTemplate;

	@RequestMapping("/hello")
    public String hello(){
        redisTemplate.opsForValue().set("per",new Person(1,"personsss"));
        Person person = (Person) redisTemplate.opsForValue().get("per");
        return person.toString() ;
	}
}

Enter your browser to http: // localhost: 8080 / redistest / hello, displays the following
Here Insert Picture Description
query in Redis client, Richard key value as per the following time, in line with our program.
Here Insert Picture Description

This article code reference: SpringBoot2.0 integrate Redis

Guess you like

Origin blog.csdn.net/Geffin/article/details/100123543
Recommended