springboot2.1.3 + redisTemplate 操作 redis 3.0.5

In recent integration springboot + redis function, had wanted to use jedit api native, finally think a little low, found a handful, boot been provided to the way we operate, that is,

Use redisTemplate or StringRedisTemplate, both are different, the following explanation can be seen

1. The relationship between the two is StringRedisTemplate inherited RedisTemplate.

2. The data are not common to both; that StringRedisTemplate only inside the management data StringRedisTemplate, RedisTemplate only the management data RedisTemplate.

3. SDR sequence strategy used by default, there are two, one is String serialization strategy, one is JDK serialization strategy.

StringRedisTemplate defaults is String serialization strategy, save the key and value are based on the sequence of this policy saved.

RedisTemplate uses a default JDK serialization strategy, save the key and value are based on the sequence of this policy saved.

Quoted from: https://blog.csdn.net/yifanSJ/article/details/79513179

 

Well, the explanation of the concept is not explained here in detail, here is how to quickly build and achieve record operating redis, look at my project structure, as shown:

 

Introducing relevant jar package, pom.xml as follows:

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.6.1</version><!--$NO-MVN-MAN-VER$-->
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.8</version><!--$NO-MVN-MAN-VER$-->
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.8</version><!--$NO-MVN-MAN-VER$-->
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.8</version><!--$NO-MVN-MAN-VER$-->
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.2</version><!--$NO-MVN-MAN-VER$-->
        </dependency>
        
    </dependencies>

 

Redis configuration parameters application.properties:

# Configure parameters redis 
# the Redis database indexes (default 0) 
spring.redis.database = 0 
# server connected to the Redis password (blank by default) 
spring.redis.password = 
# the Redis server address 
spring.redis.host = 127.0.0.1 
# Redis server port 
spring.redis.port = 6379 
# connection timeout, (ms) 
spring.redis.timeout = 5000 
# connection pool maximum number of connections (negative values no limit) 
spring.redis.lettuce.pool.max = 200 is -active 
# latency connection pool maximum blocking (negative values no limit) 
spring.redis.lettuce.pool.max -wait = -1 
# connection pool maximum idle connection 
spring.redis.lettuce.pool.max = 10 -idle 
# minimum connection pool idle connections 
spring.redis.lettuce.pool.min -idle = 0  
# cluster
# spring.redis.cluster.nodes=192.168.211.134:7000,192.168.211.134:7001,192.168.211.134:7002
#spring.redis.cluster.max-redirects=6

 

Creating RedisConfiguration categories:

package com.szl.demo.common.util;

import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
importcom.fasterxml.jackson.annotation.PropertyAccessor;
 Import com.fasterxml.jackson.databind.ObjectMapper;
 Import com.fasterxml.jackson.annotation *. ; 

@EnableCaching 
@Configuration 
public  class RedisConfiguration the extends CachingConfigurerSupport { 
    
    / ** 
     * @param The connectionFactory 
     * @return 
     * @desc Redis templates, storage key is a string, 
     * jackson2JsonRedisSerializer value is a value of the sequence 
     * / 
    public RedisTemplate redisTemplate (RedisConnectionFactory the connectionFactory) { 
        RedisTemplate redisTemplate = new newRedisTemplate (); 
        redisTemplate.setConnectionFactory (The connectionFactory); 
        
        // use Jackson2JsonRedisSerializer value to serialize and deserialize the redis value (JDK use default serialization) 
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new new Jackson2JsonRedisSerializer (Object. Class ); 
        ObjectMapper ObjectMapper = new new ObjectMapper (); 
        objectMapper.setVisibility (PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); 
        objectMapper.enableDefaultTyping (ObjectMapper.DefaultTyping.NON_FINAL); 
        jackson2JsonRedisSerializer.setObjectMapper (ObjectMapper); // use StringRedisSerializer to serialize and deserialize the redis key value
                                
        
        
        RedisSerializer redisSerializer = new StringRedisSerializer();
        // key
        redisTemplate.setKeySerializer(redisSerializer);
        redisTemplate.setHashKeySerializer(redisSerializer);
        // value
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
    
}

 

DTO categories:

package com.szl.demo.common.dto;

import java.io.Serializable;
import lombok.Data;

@Data
public class UserDto implements Serializable {
    private static final long serialVersionUID = -8858511759866491158L;
    
    private String userName;
    private Integer userAge;
    
}

 

UserService Interface:

Package com.szl.demo.service; 

Import com.szl.demo.common.dto.UserDto; 

public  interface UserService { 
    
    / ** 
     * @param UserDTO 
     * @desc redis saved to the string 
     * / 
    public  void saveUserInfoToRedis () ; 
    
    / ** 
     * @param Key 
     * @return 
     * @desc read from redis string 
     * / 
    public string getUserInfoFromRedis (string Key); 
    
    
    / ** 
     * @param UserDTO 
     * @desc redis to store objects in 
     * / 
    public  void saveUserObject (UserDTO UserDTO);
    
    / ** 
     * @param the userName 
     * @return 
     * @desc acquired from redis objects 
     * / 
    public UserDTO findUserObject (String the userName); 
    
}

 

UserServiceImpl implement an interface:

package com.szl.demo.service.impl;

import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.szl.demo.common.dto.UserDto;
import com.szl.demo.service.UserService;

@Service("userService")
public class UserServiceImpl implements UserService {
    @Resource
    private RedisTemplate redisTemplate;
    
    /**
     * @param userDto
     * @desc 将字符串保存到redis中
     * / 
    Public  void saveUserInfoToRedis () {
         // determines whether there is redis Key 
        Boolean ISEXIST = redisTemplate.hasKey ( "Demo ha" );
         IF (! ISEXIST) {
             // save key, a period of 30 seconds 
            redisTemplate.opsForValue (). set ( "demo ha", "abc123", 60 , TimeUnit.SECONDS); 
        } the else {
             // delete Key 
            redisTemplate.delete ( "Demo ha" ); 
        } 
    } 
    
    / ** 
     * @param Key 
     * @return 
     * @desc redis read in from the string 
     * /
    public String getUserInfoFromRedis (String Key) { 
        String Val = (String) redisTemplate.opsForValue () GET (Key);.
         return Val; 
    } 
    
    / ** 
     * @param UserDTO 
     * @desc redis to store objects in 
     * / 
    public  void saveUserObject (UserDTO UserDTO) {
         // determines whether there is redis Key 
        Boolean ISEXIST = redisTemplate.hasKey (userDto.getUserName ());
         iF (! ISEXIST) {
             // save key, period of 30 seconds 
            . redisTemplate.opsForValue () set ( userDto.getUserName (), UserDTO, 60 , TimeUnit.SECONDS); 
        }else {
            // 删除key
            redisTemplate.delete(userDto.getUserName());
        }
    }
    
    /**
     * @param userName
     * @return
     * @desc 从redis中获取对象
     */
    public UserDto findUserObject(String userName) {
        UserDto userDto = (UserDto) redisTemplate.opsForValue().get(userName);
        return userDto;
    }
    
}

 

Controller class:

package com.szl.demo.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.szl.demo.common.dto.UserDto;
import com.szl.demo.service.UserService;

@Controller
public class DemoController {
    @Autowired
    private UserService userService;
    
    @RequestMapping(value = "/saveUser", method = RequestMethod.POST)
    public void saveUser(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        userService.saveUserInfoToRedis();
    }
    
    @RequestMapping(value = "/getUserInfo", method = RequestMethod.GET)
    public void getUserInfo(HttpServletRequest request, HttpServletResponse response, 
            @RequestParam(value = "key", required = false) String key) {
        String msg = userService.getUserInfoFromRedis(key);
        System.out.println(msg);
    }
    
    @RequestMapping(value = "/saveUserObject", method = RequestMethod.POST)
    public void saveUserObject(HttpServletRequest request, HttpServletResponse response) {
        UserDto dto = new UserDto();
        dto.setUserName("Jimmy Shan");
        dto.setUserAge(21);
        userService.saveUserObject(dto);
    }
    
    @RequestMapping(value = "/getUserObject", method = RequestMethod.GET)
    public void getUserObject(HttpServletRequest request, HttpServletResponse response, 
            @RequestParam(value = "key", required = false) String key) {
        UserDto dto = userService.findUserObject(key);
        System.out.println("姓名: " + dto.getUserName() + ", 年龄: " + dto.getUserAge());
    }
    
}

 

At this point, we ran up to see the effect of the above is the code and configuration I tested and approved, and the other should be noted that, redis server I use 3.0.5, 2.4.5 of time before use, always connected deadlock ( win environment), toss a long time,

Finally updated version of the high solve the problem.

If I refer a friend notes, there are problems you can leave a message, please indicate the original, thank you.

 

Guess you like

Origin www.cnblogs.com/jimmyshan-study/p/11007101.html
Recommended