springboot2.1.3 + redisTemplate 操作 redis 3.0.5

Posted jimmyshan-study

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot2.1.3 + redisTemplate 操作 redis 3.0.5相关的知识,希望对你有一定的参考价值。

近期在整合springboot + redis 的功能,本来想用原生的jedit api,最后想想有点 low,搜了一把,boot已经提供给我们操作的方法,那就是

使用 redisTemplate 或 StringRedisTemplate, 两者是有区别的,可以看下面的说明

1. 两者的关系是StringRedisTemplate继承RedisTemplate。

2. 两者的数据是不共通的;也就是说StringRedisTemplate只能管理StringRedisTemplate里面的数据,RedisTemplate只能管理RedisTemplate中的数据。

3. SDR默认采用的序列化策略有两种,一种是String的序列化策略,一种是JDK的序列化策略。

StringRedisTemplate默认采用的是String的序列化策略,保存的key和value都是采用此策略序列化保存的。

RedisTemplate默认采用的是JDK的序列化策略,保存的key和value都是采用此策略序列化保存的。

引自: https://blog.csdn.net/yifanSJ/article/details/79513179

 

好了,有关概念的解释不在此处详细说明,这里只是记录如何快速搭建和实现操作redis,先看下我的工程结构,如图:

技术图片

 

引入相关jar包,pom.xml如下:

    <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参数 application.properties:

# 配置redis参数
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器连接密码(默认为空)
spring.redis.password=
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# 连接超时时间,单位(毫秒)
spring.redis.timeout=5000
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.lettuce.pool.max-active=200
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.lettuce.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.lettuce.pool.max-idle=10
# 连接池中的最小空闲连接
spring.redis.lettuce.pool.min-idle=0
# 集群
#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

 

创建RedisConfiguration类:

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;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.annotation.*;

@EnableCaching
@Configuration
public class RedisConfiguration extends CachingConfigurerSupport 
    
    /**
     * @param connectionFactory
     * @return
     * @desc redis模板,存储关键字是字符串,
     *       值jackson2JsonRedisSerializer是序列化后的值
     */
    public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) 
        RedisTemplate redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(connectionFactory);
        
        // 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = 
                                new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        
        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        RedisSerializer redisSerializer = new StringRedisSerializer();
        // key
        redisTemplate.setKeySerializer(redisSerializer);
        redisTemplate.setHashKeySerializer(redisSerializer);
        // value
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    
    

 

DTO 类:

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接口:

package com.szl.demo.service;

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

public interface UserService 
    
    /**
     * @param userDto
     * @desc 将字符串保存到redis中
     */
    public void saveUserInfoToRedis();
    
    /**
     * @param key
     * @return
     * @desc 从redis中读取字符串
     */
    public String getUserInfoFromRedis(String key);
    
    
    /**
     * @param userDto
     * @desc 将对象保存到redis中
     */
    public void saveUserObject(UserDto userDto);
    
    /**
     * @param userName
     * @return
     * @desc 从redis中获取对象
     */
    public UserDto findUserObject(String userName);
    

 

UserServiceImpl实现接口:

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() 
        // 判断redis中是否存在key
        boolean isExist = redisTemplate.hasKey("demo哈哈");
        if (!isExist) 
            // 保存key,有效期为30秒
            redisTemplate.opsForValue().set("demo哈哈", "abc123", 60, TimeUnit.SECONDS);
         else 
            // 删除key
            redisTemplate.delete("demo哈哈");
        
    
    
    /**
     * @param key
     * @return
     * @desc 从redis中读取字符串
     */
    public String getUserInfoFromRedis(String key) 
        String val = (String)redisTemplate.opsForValue().get(key);
        return val;
    
    
    /**
     * @param userDto
     * @desc 将对象保存到redis中
     */
    public void saveUserObject(UserDto userDto) 
        // 判断redis中是否存在key
        boolean isExist = redisTemplate.hasKey(userDto.getUserName());
        if (!isExist) 
            // 保存key,有效期为30秒
            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类:

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());
    
    

 

至此,我们就跑起来看效果了,以上是本人经过测试并通过的代码和配置,另外需要说明一点,redis服务器本人使用3.0.5, 之前在使用2.4.5的时候,总是连接死锁(win环境),折腾了许久,

最后还是更新高版本解决问题。

如有朋友参考本人的笔记,有问题可以留言,转载请注明原著,谢谢。

 

以上是关于springboot2.1.3 + redisTemplate 操作 redis 3.0.5的主要内容,如果未能解决你的问题,请参考以下文章

springboot2.1.3 本地加载jar包+打包载入本地jar

springboot2.1.3整合websocket和websocket-security支持跨域连接

安装不上vc_redist的解决办法

安装不上vc_redist的解决办法

分发原始 msvcp.dll 或安装 vc_redist.exe

C# 检查已安装的 .NET Framework 和 MS Visual C++ Redist 版本