I’ve been lazy for a few days. I haven’t written Springboot for a few days. It’s not that there’s nothing to write about, but it’s really hard to stick to one thing.

I took time out today to make a small example of springBoot’s integration with Redis.

First of all, do a good job in the local installation of a Redis, specific steps can be baidu, and then start redis. The following page appears and the startup is successful.

Then create a new project and add the redis dependency. The POM file is as follows:

<? xml version="1.0" encoding="UTF-8"? > <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> < modelVersion > 4.0.0 < / modelVersion > < groupId > com. Dalaoyang < / groupId > < artifactId > springboot_redis < / artifactId > < version > 0.0.1 - the SNAPSHOT < / version > < packaging > jar < / packaging > < name > springboot_redis < / name > <description>springboot_redis</description> <parent> <groupId>org.springframework.boot</groupId> The < artifactId > spring - the boot - starter - parent < / artifactId > < version > 1.5.9. RELEASE < / version > < relativePath / > <! -- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> < project. Reporting. OutputEncoding > utf-8 < / project. Reporting. OutputEncoding > < Java version > 1.8 < / Java version > </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId>  <scope>test</scope>
		</dependency>

	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>


</project>
Copy the code

Then add the redis configuration to application.properties:

# # the port number
server.port=8888

# Redis database index (default: 0)
spring.redis.database=0 
# Redis server address
spring.redis.host=localhost
# Redis server connection port
spring.redis.port=6379 
# Redis server connection password (default: null)
spring.redis.password=
Maximum number of connections in the connection pool (negative value indicates no limit)
spring.redis.pool.max-active=8 
# Connection pool maximum blocking wait time (negative value indicates no limit)
spring.redis.pool.max-wait=-1 
# Maximum free connection in the connection pool
spring.redis.pool.max-idle=8 
# Minimum free connection in the connection pool
spring.redis.pool.min-idle=0 
# Connection timeout (milliseconds)
spring.redis.timeout=0

Copy the code

RedisConfig Configuration class, in which @enablecaching is enabled

package com.dalaoyang.config; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.CachingConfigurerSupport; 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.core.RedisTemplate; /** * @author dalaoyang * @Description * @project springboot_learn * @package com.dalaoyang.config * @email [email protected] * @date 2018/4/18 */ @configuration @enablecaching // EnableCaching public class RedisConfig extends CachingConfigurerSupport { @Bean public CacheManager cacheManager(RedisTemplate<?,?> redisTemplate) { CacheManager cacheManager = new RedisCacheManager(redisTemplate);return cacheManager;
    }

    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>();
        redisTemplate.setConnectionFactory(factory);
        returnredisTemplate; }}Copy the code

Because of the simple integration, I only created a RedisService to access the cached data. In the actual project, you can create an interface, impL, and so on. The code is as follows:

package com.dalaoyang.service;
import javax.annotation.Resource;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

/**
 * @author dalaoyang
 * @Description
 * @project springboot_learn
 * @package com.dalaoyang.service
 * @email [email protected]
 * @date 2018/4/18
 */
@Service
public class RedisService {
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    public void setRedisSerializer RedisSerializer =new StringRedisSerializer(); (String key, Object value) {// Change the key encoding problem in redis. redisTemplate.setKeySerializer(redisSerializer); ValueOperations<String,Object> vo = redisTemplate.opsForValue(); vo.set(key, value); } public Object get(String key) { ValueOperations<String,Object> vo = redisTemplate.opsForValue();returnvo.get(key); }}Copy the code

Physical class City:

package com.dalaoyang.entity;

import java.io.Serializable;

/**
 * @author dalaoyang
 * @Description
 * @project springboot_learn
 * @package com.dalaoyang.Entity
 * @email [email protected]
 * @date 2018/4/7
 */
public class City implements Serializable {
    private int cityId;
    private String cityName;
    private String cityIntroduce;

    public City(int cityId, String cityName, String cityIntroduce) {
        this.cityId = cityId;
        this.cityName = cityName;
        this.cityIntroduce = cityIntroduce;
    }

    public City(String cityName, String cityIntroduce) {
        this.cityName = cityName;
        this.cityIntroduce = cityIntroduce;
    }

    public City() {
    }

    public int getCityId() {
        return cityId;
    }

    public void setCityId(int cityId) {
        this.cityId = cityId;
    }

    public String getCityName() {
        return cityName;
    }

    public void setCityName(String cityName) {
        this.cityName = cityName;
    }

    public String getCityIntroduce() {
        return cityIntroduce;
    }

    public void setCityIntroduce(String cityIntroduce) { this.cityIntroduce = cityIntroduce; }}Copy the code

The test class CityController

package com.dalaoyang.controller; import com.dalaoyang.entity.City; import com.dalaoyang.service.RedisService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; /** * @author dalaoyang * @Description * @project springboot_learn * @package com.dalaoyang.controller * @email [email protected] * @date 2018/4/7 */ @RestController public class CityController { @Autowired private RedisService redisService; //http://localhost:8888/saveCity? CityName = Beijing &cityId=1 @getMapping (value ="saveCity")
    public String saveCity(int cityId,String cityName,String cityIntroduce){
        City city = new City(cityId,cityName,cityIntroduce);
        redisService.set(cityId+"",city);
        return "success"; } //http://localhost:8888/getCityById? cityId=1 @GetMapping(value ="getCityById")
    public City getCity(int cityId){
        City city = (City) redisService.get(cityId+"");
        returncity; }}Copy the code

Here configuration basically completed, and then start the project at http://localhost:8888/saveCity? CityName = Beijing &cityId=18 Introduce the capital of China &cityId=18

Found the error, look at the background, as follows

Found no serialization is entity class, and then to the City class serialization, and then go to http://localhost:8888/saveCity? CityName = Beijing &cityId=18

Then look at Redis and find that the key value is not encoded correctly

Add to RedisService

RedisSerializer RedisSerializer =new StringRedisSerializer(); // Modify the key encoding problem in redis. redisTemplate.setKeySerializer(redisSerializer);Copy the code

When looking at the redis key, I found that the code is correct

Source download: Old Yang code cloud

Personal website: dalaoyang.cn