博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SpringBoot集成Redis做缓存处理
阅读量:5112 次
发布时间:2019-06-13

本文共 7814 字,大约阅读时间需要 26 分钟。

(1)首先,在springboot项目pom.xml中引入redis依赖

<dependency>

  <groupId>redis.clients</groupId>
  <artifactId>jedis</artifactId>
  <version>2.9.0</version>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

(2)将redis需要的配置写入application.properties中方便修改时不改动代码

# Redis数据库索引(默认为0)spring.redis.database=0# Redis服务器地址spring.redis.host=127.0.0.1# Redis服务器连接端口spring.redis.port=6379# Redis服务器连接密码(默认为空)spring.redis.password=# 连接池最大连接数(使用负值表示没有限制)spring.redis.pool.max-active=8# 连接池最大阻塞等待时间(使用负值表示没有限制)spring.redis.pool.max-wait=-1# 连接池中的最大空闲连接spring.redis.pool.max-idle=8# 连接池中的最小空闲连接spring.redis.pool.min-idle=0# 连接超时时间(毫秒)spring.redis.timeout=0# 设置key失效时间(秒)spring.redis.expire=600

(3)在springboot中注册Redis配置,在启动时执行该配置

RedisConfig.java(放在springboot能扫描到的包下)

package com.zxyp.redis;import org.springframework.beans.factory.annotation.Value;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.core.StringRedisTemplate;import redis.clients.jedis.JedisPoolConfig;@Configurationpublic class RedisConfig {	@Value("${spring.redis.host}")	private String hostname;	@Value("${spring.redis.password}")	private String password;	@Value("${spring.redis.port}")	private Integer port;	@Value("${spring.redis.database}")	private Integer database;	@Bean	@ConfigurationProperties(prefix = "spring.redis")	public JedisPoolConfig getRedisConfig() {		JedisPoolConfig config = new JedisPoolConfig();		return config;	}	@Bean	@ConfigurationProperties(prefix = "spring.redis")	public JedisConnectionFactory getConnectionFactory(){		JedisConnectionFactory factory = new JedisConnectionFactory();		JedisPoolConfig config = getRedisConfig();		factory.setPoolConfig(config);		factory.setHostName(hostname);		factory.setPassword(password);		factory.setPort(port);		factory.setDatabase(database);		System.out.println("JedisConnectionFactory bean init success.");		return factory;	}	@Bean	public RedisTemplate
getRedisTemplate() { RedisTemplate
template = new StringRedisTemplate(getConnectionFactory()); return template; }}

(4)根据需求写对应的redis缓存服务接口,我这里写了get取缓存,set存缓存,expire给缓存设置对应的失效时间,flushall清空所有缓存,delete清空对应key的缓存

RedisDao.java (service层接口)

package com.zxyp.redis;public interface RedisDao {	public void set(String key,String value);		public String get(String key);		public void delete(String key);	public void expire(String key, Long value);	void flushall();}

(5)实现Service层RedisDao接口

RedisDaoImpl.java

package com.zxyp.redis.impl;import javax.annotation.Resource;import org.springframework.dao.DataAccessException;import org.springframework.data.redis.connection.RedisConnection;import org.springframework.data.redis.core.RedisCallback;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.serializer.RedisSerializer;import org.springframework.stereotype.Repository;import com.zxyp.redis.RedisDao;@Repository("springdatadao")public class SpringDataRedisDaoImpl implements RedisDao {	@Resource	private RedisTemplate
redisTemplate; @Override public void set(String key, String value) { redisTemplate.execute(new RedisCallback
() { @Override public Boolean doInRedis(RedisConnection connection) throws DataAccessException { RedisSerializer
serializer = redisTemplate.getStringSerializer(); connection.set(serializer.serialize(key), serializer.serialize(value)); return true; } }); } @Override public String get(String key) { try { String result = redisTemplate.execute(new RedisCallback
() { @Override public String doInRedis(RedisConnection connection) throws DataAccessException { RedisSerializer
serializer = redisTemplate.getStringSerializer(); byte[] value = connection.get(serializer.serialize(key)); return serializer.deserialize(value); } }); return result; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return "destory"; } @Override public void delete(String key) { redisTemplate.execute(new RedisCallback
() { @Override public Object doInRedis(RedisConnection connection) throws DataAccessException { connection.del(key.getBytes()); return null; } }); } @Override public void expire(String key, Long value) { redisTemplate.execute(new RedisCallback
() { @Override public Boolean doInRedis(RedisConnection connection) throws DataAccessException { RedisSerializer
serializer = redisTemplate.getStringSerializer(); connection.expire(serializer.serialize(key), value); return true; } }); } @Override public void flushall() { redisTemplate.execute(new RedisCallback
() { @Override public Object doInRedis(RedisConnection connection) throws DataAccessException { connection.flushAll(); return null; } }); }}

说明:get之所以要检测异常,是因为redis服务可能会挂掉,如果服务挂掉可以通过返回值判断,并作出处理,不会影响业务

(6)Redis服务的使用,在对应需要调用服务的Controller中注入该Service层接口,调用对应的方法即可,这里是我使用的示例,仅供参考

ContenController.java (此Controller引用了自己项目封装的pager,不能直接使用,只是作为使用redis的参考)

package com.zxyp.controller;import java.util.List;import java.util.Map;import javax.annotation.Resource;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.beans.factory.annotation.Value;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;import com.alibaba.fastjson.JSON;import com.zxyp.ContentService;import com.zxyp.UserService;import com.zxyp.base.web.BaseController;import com.zxyp.base.web.ResultEntity;import com.zxyp.dao.entity.Pager;import com.zxyp.domain.Govtheme;import com.zxyp.redis.RedisDao;@RestController@SuppressWarnings("rawtypes") @RequestMapping("/shareContent")public class ContenController {	@Autowired	private ContentService contentService;	@Autowired	private UserService userService;		@Resource	@Qualifier("springdatadao")	private RedisDao redisDao;		@Value("${spring.redis.expire}")	private Long expiretime;    /**     * 查询部门列表内容     * @return     */    @RequestMapping(value = "/shareDepartPager",method= RequestMethod.POST)    public ResultEntity queryDepartContentPager(@RequestBody Map map){    	    	int pageSize = Integer.parseInt(map.get("pageSize")+"");    	int currentPage = Integer.parseInt(map.get("currentPage")+"");    	String type = map.get("type")+"";    	String userid = map.get("userid")+"";    	String fileid = (String)map.get("fileid");    	String id = String.valueOf(map.get("id"));    	String redisKey = String.valueOf(currentPage)+String.valueOf(pageSize)+type+userid+fileid+id;    	Pager pager = null;    	String pageStr = redisDao.get(redisKey);    	if(!"destory".equals(pageStr)) {    		if(pageStr != null) {    			pager = JSON.parseObject(pageStr,Pager.class);    		} else {    			pager = new Pager();    	    	pager.setPageSize(pageSize);    	    	pager.setCurrentPage(currentPage);    			pager = contentService.querySharePager(map, pager);    			redisDao.set(redisKey, JSON.toJSONString(pager));    			redisDao.expire(redisKey, expiretime);    		}		} else {			pager = new Pager();	    	pager.setPageSize(pageSize);	    	pager.setCurrentPage(currentPage);			pager = contentService.querySharePager(map, pager);		}		    	return ResultEntity.createSuccessInstance(pager);    }}

  

 

转载于:https://www.cnblogs.com/mituxiaogaoyang/p/8393471.html

你可能感兴趣的文章
【Linux】入门篇 环境搭建
查看>>
poj2569
查看>>
使用mmap在内存中读写文件
查看>>
使用pygal_maps_world.i18n中数据画各大洲地图
查看>>
sql server必知多种日期函数时间格式转换
查看>>
ListView如何获取点击单元格内容
查看>>
jQuery EasyUI 的下拉选择combobox后台动态赋值
查看>>
(转)游戏引擎中三大及时光照渲染方法介绍(以unity3d为例)
查看>>
timeline时间轴进度“群英荟萃”
查看>>
python map函数用法
查看>>
ios之申请后台延时执行和做一个假后台的方法(系统进入长时间后台后,再进入前台部分功能不能实现)...
查看>>
编码命名规范
查看>>
耿丹16-1上半学期助教总结
查看>>
python if else elif statement
查看>>
网络编程
查看>>
文本隐藏(图片代替文字)
查看>>
three.map.control
查看>>
二叉树的深度
查看>>
java面试题
查看>>
提高码力专题(未完待续)
查看>>