Spring集成Redis

标签:?redis??Spring-Redis??RedisUtils??Spring集成Redis??ssm redis

概述:

? ? ? ??本篇文章主要展示如何在Spring中集成Redis,并通过一个接口展示Redis在Java项目中的实际应用。项目中需要用到的redis操作的相关工具类在上一篇文章中已经做了非常详细的介绍,本篇文章不再贴出有关代码。

? ? ? ? 工具类参考地址:https://blog.csdn.net/m0_38045882/article/details/80431426

注:在进行如下操作前请先下载安装并启动redis

1、搭建SSM框架

? ? ? 有关SSM框架搭建的相关知识请参考其它文章

2、项目中引入Jedis相关jar包

? ? ? pom.xml中加入依赖如下图所示

    
    
        org.springframework.data
        spring-data-redis
        1.6.0.RELEASE
    
    
        redis.clients
        jedis
        2.7.3
    
    

3、项目中引入redisConfig.properties配置文件如下所示

#服务ip
redis.ip=127.0.0.1
#服务端口
redis.port=6379
#超时时间:单位ms
redis.timeout=3000
#授权密码
redis.password=jwang
#最大连接数:能够同时建立的“最大链接个数”  
redis.pool.maxActive=200
#最大空闲数:空闲链接数大于maxIdle时,将进行回收
redis.pool.maxIdle=20
#最小空闲数:低于minIdle时,将创建新的链接
redis.pool.minIdle=5
#最大等待时间:单位ms
redis.pool.maxWait=3000
#使用连接时,检测连接是否成功     
redis.pool.testOnBorrow=true
#返回连接时,检测连接是否成功 
redis.pool.testOnReturn=true

注意:将该文件放置到classpath下,与我们熟知的application.properties文件路径相同

4、Redis操作相关工具类编写

? ? ? RedisUtils.java部分代码如下:

package com.jwang.ssmxml.common.redis;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import com.jwang.ssmxml.common.util.PropertiesUtils;
import com.jwang.ssmxml.common.util.SerializeUtils;

import redis.clients.jedis.BinaryClient.LIST_POSITION;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.util.SafeEncoder;

/**
 * redis操作工具类
 * @author jwang
 *
 */
public class RedisUtils 
{
    private static Logger logger = LoggerFactory.getLogger(RedisUtils.class);
    
    //获取连接参数
    private static final String PROPETIES_PATH = "config/redisConfig.properties";
	
	private static final Properties PROP = PropertiesUtils.getProperties(PROPETIES_PATH);
	
	private static final String REDIS_ADDR = PROP.getProperty("redis.ip");
	
	private static final String REDIS_PORT = PROP.getProperty("redis.port");
	
	private static final String REDIS_MAXACTIVE = PROP.getProperty("redis.pool.maxActive");
	
	private static final String REDIS_MAXIDLE = PROP.getProperty("redis.pool.maxIdle");
	
	private static final String REDIS_MAXWAIt = PROP.getProperty("redis.pool.maxWait");
	
	private static final String REDIS_TIMEOUT = PROP.getProperty("redis.timeout");
	
	private static final String REDIS_PASSWORD = PROP.getProperty("redis.password");
	
	private static final String REDIS_TESTONBORROW = PROP.getProperty("redis.pool.testOnBorrow");
    
	private static JedisPool jedisPool = null;
    
	//初始化redis连接池
    static
    {
        try 
        {
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(Integer.parseInt(REDIS_MAXACTIVE));
            config.setMaxIdle(Integer.parseInt(REDIS_MAXIDLE));
            config.setMaxWaitMillis(Integer.parseInt(REDIS_MAXWAIt));
            config.setTestOnBorrow(Boolean.parseBoolean(REDIS_TESTONBORROW));
            jedisPool = new JedisPool(config, REDIS_ADDR, Integer.parseInt(REDIS_PORT), 
            		Integer.parseInt(REDIS_TIMEOUT), REDIS_PASSWORD);
        }
        catch (Exception e)
        {
        	logger.error("Jedis pool create fail!!!");
            e.printStackTrace();
        }
    }

    /**
     * 获取Jedis实例
     * @return
     */
    public static synchronized Jedis getJedis() 
    {
        try
        {
            if (jedisPool != null) 
            {
                Jedis resource = jedisPool.getResource();
                return resource;
            } 
            else 
            {
                return null;
            }
        }
        catch (Exception e)
        {
        	logger.error("Jedis get fail!!!");
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 释放jedis资源
     * @param jedis
     */
    public static void closeResource(final Jedis jedis)
    {
        if (jedis != null)
        {
        	jedis.close();
        }
    }

    /**
     * 获取redis键值-object
     * 
     * @param key
     * @return
     */
    public static Object getObject(String key) 
    {
        Jedis jedis = null;
        try 
        {
            jedis = jedisPool.getResource();
            byte[] bytes = jedis.get(key.getBytes());
            if(!StringUtils.isEmpty(bytes))
            {
                return SerializeUtils.unserialize(bytes);
            }
        }
        catch (Exception e) 
        {
            logger.error("getObject获取redis键值异常:key=" + key + " cause:" + e.getMessage());
        } 
        finally
        {
            jedis.close();
        }
        return null;
    }

    /**
     * 设置redis-object
     * @param key
     * @param value
     * @return
     */
    public static String setObject(String key, Object value) 
    {
        Jedis jedis = null;
        try
        {
            jedis = jedisPool.getResource();
            return jedis.set(key.getBytes(), SerializeUtils.serialize(value));
        }
        catch (Exception e)
        {
            logger.error("setObject设置redis键值异常:key=" + key + " value=" + value + " cause:" + e.getMessage());
            return null;
        } 
        finally
        {
            if(jedis != null)
            {
                jedis.close();
            }
        }
    }
}

注意:该工具类只截取了部分方法,工具类中用到的PropertiesUtils.java工具类及SerializeUtils.java工具类参看文章开头提供的地址。

5、编写接口,使用Redis

UserController.java中截取接口代码如下:

package com.jwang.ssmxml.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jwang.ssmxml.beans.dao.UserDao;
import com.jwang.ssmxml.beans.dto.UserDto;
import com.jwang.ssmxml.beans.dto.UserListQueryDto;
import com.jwang.ssmxml.beans.vo.UserInfoVo;
import com.jwang.ssmxml.common.constant.ResultCode;
import com.jwang.ssmxml.common.exception.ValidateException;
import com.jwang.ssmxml.service.UserService;
import com.jwang.ssmxml.validate.UserValidate;

/**
 * @author jwang
 *
 */
@Controller
@RequestMapping(value="/user")
public class UserController extends BaseController
{
	
	@Autowired
	private UserService userService;
	
	/**
	 * 分页查询用户列表
	 * @param response
	 * @param userListQueryDto
	 * @throws IOException 
	 */
	@RequestMapping(value="/getUserList", method=RequestMethod.POST)
	public void getUserList(HttpServletResponse response, @RequestBody
			UserListQueryDto userListQueryDto) throws IOException
	{
		UserInfoVo userInfoVo = userService.getUserList(userListQueryDto);
		
		returnToPage(response, gson.toJson(bulidResultObj(ResultCode.SUCCESS_CODE, null, userInfoVo)));
	}
}	

UserService.java如下所示:

package com.jwang.ssmxml.service;

import com.jwang.ssmxml.beans.dao.UserDao;
import com.jwang.ssmxml.beans.dto.UserDto;
import com.jwang.ssmxml.beans.dto.UserListQueryDto;
import com.jwang.ssmxml.beans.vo.UserInfoVo;

public interface UserService 
{	
	UserInfoVo getUserList(UserListQueryDto userListQueryDto);
}

UserServiceImpl.java如下所示:

package com.jwang.ssmxml.service.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jwang.ssmxml.beans.dao.UserDao;
import com.jwang.ssmxml.beans.dto.UserDto;
import com.jwang.ssmxml.beans.dto.UserListQueryDto;
import com.jwang.ssmxml.beans.vo.UserInfoVo;
import com.jwang.ssmxml.common.redis.RedisUtils;
import com.jwang.ssmxml.mapper.UserMapper;
import com.jwang.ssmxml.service.UserService;

@Service
public class UserServiceImpl implements UserService
{
	private static final Logger LOGGER = Logger.getLogger(UserServiceImpl.class);
	
	@Autowired
	private UserMapper userMapper;

	@Override
	public UserInfoVo getUserList(UserListQueryDto userListQueryDto) 
	{
		//先查询redis,如果有直接从redis中取,没有则查询数据库,然后写入redis
		
		UserInfoVo userInfoVo = null;
		
		userInfoVo = (UserInfoVo)RedisUtils.getObject("userInfoListKey");
		
		if(userInfoVo == null)
		{
			LOGGER.info("redis中无数据从数据库中获取......");
			userInfoVo = new UserInfoVo();
			//获取记录条数
			int count = userMapper.getUserCount(userListQueryDto);
			
			userListQueryDto.getPageInfo().setFrom(userListQueryDto.getPageInfo().getCurrentPage(),
					userListQueryDto.getPageInfo().getSize());
			
			userListQueryDto.getPageInfo().setTotal(count);
			
			List userList = userMapper.getUserList(userListQueryDto);
			
			userInfoVo.setPageInfo(userListQueryDto.getPageInfo());
			
			userInfoVo.setUserList(userList);
		
			RedisUtils.setObject("userInfoListKey", userInfoVo);
		}
		else
		{
			LOGGER.info("redis中有数据,从redis中获取数据......");
		}
		
		return userInfoVo;
	}

}

6、接口调用测试:

? ? ?使用postman调用接口,输入参数如下所示:

第一次调用时后台日志:

第二次调用时后台日志:

提醒:redis中存储的Java对象需要序列化后才能存储到redis中,而这些需要被序列化的对象的类本身需要实现Serializable接口。否则序列化时会报错

?

原文链接:加载失败,请重新获取