SpringBoot使用redis详尽教程

一、Redis

redis是一个key-value存储系统它支持存储的value类型很多,包括string(字符串)、list(链表)、set(集合)、zset(sorted set --有序集合)和hash(哈希类型)。这些数据类型都支持push/pop、add/remove及取交集并集和差集及更丰富的操作,而且这些操作都是原子性的。

二、Windows下安装Redis服务

1、要安装Redis,首先要获取安装包。Windows的Redis安装包需要到以下GitHub链接找到。链接:https://github.com/MSOpenTech/redis。打开网站后,找到Release,点击前往下载页面。

2、在下载网页中,找到最后发行的版本(此处是3.2.100)。找到Redis-x64-3.2.100.msi和Redis-x64-3.2.100.zip,点击下载(此处下载msi版本)。

3、双击刚下载好的msi格式的安装包(Redis-x64-3.2.100.msi)开始安装。

4、选择“同意协议”,点击下一步继续。

5、选择“添加Redis目录到环境变量PATH中”,这样方便系统自动识别Redis执行文件在哪里。

6、端口号可保持默认的6379,并选择防火墙例外,从而保证外部可以正常访问Redis服务。

7、设定最大值存储空间。作为实验和学习,100M足够了。

8、点击安装,正式的安装过程开始。稍等一会即可完成。

9、安装完毕后,点击“开始”>右击“计算机”>选择“管理”。在左侧栏中依次找到并点击“计算机管理(本地)”>服务和应用程序>服务。再在右侧找到Redis名称的服务,查看启动情况。如未启动,则手动启动之。正常情况下,服务应该正常启动并运行了。

10、最后来测试一下Redis是否正常提供服务。进入Redis的目录,输入redis-cli并回车。(redis-cli是客户端程序)如图正常提示进入,并显示正确端口号,则表示服务已经启动。

 

11、实际测试一下读写。输入set mykey "I love you all!”并回车,用来保存一个键值。再输入get mykey,获取刚才保存的键值。

三、redis-server.exe redis.windows.conf启动redis问题

    遇到问题:# Creating Server TCP listening socket *:6379: bind: No such file or directory

    解决方案:1. redis-cli.exe    

                      2. shutdown    //关闭redis

                      3. exit    

                      4. redis-server.exe redis.windows.conf   //重启redis

四、redis可视化工具

RedisDesktopManager

五、SpringBoot使用redis存储

1、pom 依赖  

<!-- Spring Boot Redis依赖 -->
<!-- 注意:1.5版本的依赖和2.0的依赖不一样,注意看哦 1.5我记得名字里面应该没有“data”, 2.0必须是“spring-boot-starter-data-redis” 这个才行 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <!-- 1.5的版本默认采用的连接池技术是jedis 2.0以上版本默认连接池是lettuce, 在这里采用jedis,所以需要排除lettuce的jar -->
    <exclusions>
        <exclusion>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </exclusion>
        <exclusion>
           <groupId>io.lettuce</groupId>
           <artifactId>lettuce-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<!-- 添加jedis客户端 -->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>

<!--spring2.0集成redis所需common-pool2 -->
<!-- 必须加上,jedis依赖此 -->
<!-- spring boot 2.0 的操作手册有标注 大家可以去看看 地址是:https://docs.spring.io/spring-boot/docs/2.0.3.RELEASE/reference/htmlsingle/ -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency> 

2、application.properties 配置文件

#redis
spring.jpa.database=0
spring.redis.host=127.0.0.1
spring.redis.password=
spring.redis.port=6379
# 数据库连接超时时间,2.0 中该参数的类型为Duration,这里在配置的时候需要指明单位
spring.redis.timeout=10000

# 连接池配置,2.0中直接使用jedis或者lettuce配置连接池
# 最大活跃连接数,负数为不限制
spring.redis.jedis.pool.max-active=8
# 等待可用连接的最大时间,负数为不限制
spring.redis.jedis.pool.max-wait=-1
# 最大空闲连接数
spring.redis.jedis.pool.max-idle=8
# 最小空闲连接数
spring.redis.jedis.pool.min-idle=0

3、RedisConfiguration配置文件

package com.sjx.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.CacheErrorHandler;
import org.springframework.cache.interceptor.KeyGenerator;
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.jedis.JedisConnectionFactory;
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 redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @ClassName: RedisConfiguration
 * @Description:TODO(这里用一句话描述这个类的作用)
 * @author: 沈均晓
 * @date: 2018年9月19日 上午11:18:33
 */
@Configuration
// 必须加,使配置生效
@EnableCaching
public class RedisConfiguration extends CachingConfigurerSupport {

	/**
	 * Logger
	 */
	private static final Logger logger = LoggerFactory.getLogger(RedisConfiguration.class);

	@Autowired
	private JedisConnectionFactory jedisConnectionFactory;

	@Bean
	public KeyGenerator keyGenerator() {
		// 设置自动key的生成规则,配置spring boot的注解,进行方法级别的缓存
		// 使用:进行分割,可以很多显示出层级关系
		// 这里其实就是new了一个KeyGenerator对象,只是这是lambda表达式的写法,我感觉很好用,大家感兴趣可以去了解下
		return (target, method, params) -> {
			StringBuilder sb = new StringBuilder();
			sb.append(target.getClass().getName());
			sb.append(":");
			sb.append(method.getName());
			for (Object obj : params) {
				sb.append(":" + String.valueOf(obj));
			}
			String rsToUse = String.valueOf(sb);
			logger.info("自动生成Redis Key -> [{}]", rsToUse);
			return rsToUse;
		};
	}

	@Bean
	public CacheManager cacheManager() {
		// 初始化缓存管理器,在这里我们可以缓存的整体过期时间什么的,我这里默认没有配置
		logger.info("初始化 -> [{}]", "CacheManager RedisCacheManager Start");
		RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager.RedisCacheManagerBuilder
				.fromConnectionFactory(jedisConnectionFactory);
		return builder.build();
	}

	@Bean
	public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory jedisConnectionFactory) {
		// 设置序列化
		Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
		ObjectMapper om = new ObjectMapper();
		om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
		om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
		jackson2JsonRedisSerializer.setObjectMapper(om);
		// 配置redisTemplate
		RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
		redisTemplate.setConnectionFactory(jedisConnectionFactory);
		RedisSerializer stringSerializer = new StringRedisSerializer();
		redisTemplate.setKeySerializer(stringSerializer); // key序列化
		redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); // value序列化
		redisTemplate.setHashKeySerializer(stringSerializer); // Hash key序列化
		redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); // Hash value序列化
		redisTemplate.afterPropertiesSet();
		return redisTemplate;
	}

	@Override
	@Bean
	public CacheErrorHandler errorHandler() {
		// 异常处理,当Redis发生异常时,打印日志,但是程序正常走
		logger.info("初始化 -> [{}]", "Redis CacheErrorHandler");
		CacheErrorHandler cacheErrorHandler = new CacheErrorHandler() {
			@Override
			public void handleCacheGetError(RuntimeException e, Cache cache, Object key) {
				logger.error("Redis occur handleCacheGetError:key -> [{}]", key, e);
			}

			@Override
			public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) {
				logger.error("Redis occur handleCachePutError:key -> [{}];value -> [{}]", key, value, e);
			}

			@Override
			public void handleCacheEvictError(RuntimeException e, Cache cache, Object key) {
				logger.error("Redis occur handleCacheEvictError:key -> [{}]", key, e);
			}

			@Override
			public void handleCacheClearError(RuntimeException e, Cache cache) {
				logger.error("Redis occur handleCacheClearError:", e);
			}
		};
		return cacheErrorHandler;
	}

	/**
	 * 此内部类就是把yml的配置数据,进行读取,创建JedisConnectionFactory和JedisPool,以供外部类初始化缓存管理器使用
	 * 不了解的同学可以去看@ConfigurationProperties和@Value的作用
	 *
	 */
	@ConfigurationProperties
	class DataJedisProperties {
		@Value("${spring.redis.host}")
		private String host;
		@Value("${spring.redis.password}")
		private String password;
		@Value("${spring.redis.port}")
		private int port;
		@Value("${spring.redis.timeout}")
		private int timeout;
		@Value("${spring.redis.jedis.pool.max-idle}")
		private int maxIdle;
		@Value("${spring.redis.jedis.pool.max-wait}")
		private long maxWaitMillis;

		@Bean
		JedisConnectionFactory jedisConnectionFactory() {
			logger.info("Create JedisConnectionFactory successful");
			JedisConnectionFactory factory = new JedisConnectionFactory();
			factory.setHostName(host);
			factory.setPort(port);
			factory.setTimeout(timeout);
			factory.setPassword(password);
			return factory;
		}

		@Bean
		public JedisPool redisPoolFactory() {
			logger.info("JedisPool init successful,host -> [{}];port -> [{}]", host, port);
			JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
			jedisPoolConfig.setMaxIdle(maxIdle);
			jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);

			JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password);
			return jedisPool;
		}
	}

}

4、在实现类中使用

package com.sjx.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.sjx.dao.AttachmentDao;
import com.sjx.entity.Attachment;
import com.sjx.service.AttachmentService;
import com.sjx.util.ResultMap;

@Service
public class AttachmentServiceImpl implements AttachmentService {

	@Resource
	private AttachmentDao attachmentdao;

	@Autowired
	StringRedisTemplate stringRedisTemplate;

	@Override
	public ResultMap insertSelective(Attachment attachment) {
		// TODO Auto-generated method stub
		int insert = attachmentdao.insert(attachment);
		if (insert < 0) {
			return ResultMap.error("添加失败");
		}
		return ResultMap.ok("添加成功");
	}

	@Override
	public ResultMap deleteByPrimaryKey(Long id) {
		// TODO Auto-generated method stub
		int deleteByPrimaryKey = attachmentdao.deleteByPrimaryKey(id);
		if (deleteByPrimaryKey < 0) {
			return ResultMap.error("删除失败");
		}
		return ResultMap.ok("删除成功");
	}

	@Override
	public ResultMap selectByPrimaryKey(Long id) {
		Attachment selectByPrimaryKey = attachmentdao.selectByPrimaryKey(id);
		stringRedisTemplate.opsForValue().append("attachment",JSON.toJSONString(selectByPrimaryKey));
		ResultMap resultMap = new ResultMap();
		resultMap.put("Attachment", selectByPrimaryKey);
		return resultMap;
	}

	@Override
	public ResultMap SelectiveSelectByAttachment(Attachment attachment) {
		List<Attachment> selectiveSelectByAttachment = attachmentdao.SelectiveSelectByAttachment(attachment);
		stringRedisTemplate.opsForList().leftPush("attachmentList", JSON.toJSONString(selectiveSelectByAttachment));
		ResultMap resultMap = new ResultMap();
		resultMap.put("Attachment", selectiveSelectByAttachment);
		return resultMap;
	}

	@Override
	public ResultMap updateByPrimaryKeySelective(Attachment attachment) {
		int updateByPrimaryKeySelective = attachmentdao.updateByPrimaryKeySelective(attachment);
		if (updateByPrimaryKeySelective < 0) {
			return ResultMap.error("更新失败");
		}
		return ResultMap.ok("更新成功");
	}

}

附加:ResultMap工具类

package com.sjx.util;

import java.util.HashMap;
import java.util.Map;

/**
 * 
 * @ClassName:  ResultMap    
 * @Description: 返回数据通用处理   
 * @author: 沈均晓   
 * @date: 2018年9月21日 上午11:54:14
 */
public class ResultMap extends HashMap<String, Object> {
	private static final long serialVersionUID = 1L;

	public ResultMap() {
		put("code", 200);
		put("msg", "操作成功");
	}

	public static ResultMap error() {
		return error(201, "操作失败");
	}

	public static ResultMap error(String msg) {
		return error(500, msg);
	}

	public static ResultMap error(int code, String msg) {
		ResultMap resultMap = new ResultMap();
		resultMap.put("code", code);
		resultMap.put("msg", msg);
		return resultMap;
	}
	
	public static ResultMap error(String code, String msg) {
		ResultMap resultMap = new ResultMap();
		resultMap.put("code", code);
		resultMap.put("msg", msg);
		return resultMap;
	}

	public static ResultMap ok(String msg) {
		ResultMap resultMap = new ResultMap();
		resultMap.put("msg", msg);
		return resultMap;
	}

	public static ResultMap ok(Map<String, Object> map) {
		ResultMap resultMap = new ResultMap();
		resultMap.putAll(map);
		return resultMap;
	}

	public static ResultMap ok() {
		return new ResultMap();
	}

	@Override
	public ResultMap put(String key, Object value) {
		super.put(key, value);
		return this;
	}
}

猜你喜欢

转载自blog.csdn.net/Shen_Junxiao/article/details/82799292