SpringBoot集成Redis做缓存处理
(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; @Configuration public 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<String, String> redisTemplate; @Override public void set(String key, String value) { redisTemplate.execute(new RedisCallback<Boolean>() { @Override public Boolean doInRedis(RedisConnection connection) throws DataAccessException { RedisSerializer<String> 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<String>() { @Override public String doInRedis(RedisConnection connection) throws DataAccessException { RedisSerializer<String> 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<Object>() { @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<Boolean>() { @Override public Boolean doInRedis(RedisConnection connection) throws DataAccessException { RedisSerializer<String> serializer = redisTemplate.getStringSerializer(); connection.expire(serializer.serialize(key), value); return true; } }); } @Override public void flushall() { redisTemplate.execute(new RedisCallback<Object>() { @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); } }