本文主要是介绍八、springboot缓存之Redis,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
八、springboot缓存之Redis
- 无序列化
- 1、引入Redis依赖
- 2、配置Redis依赖
- 3、创建RedisCacheManager
- 4、创建RedisCache
- 5、创建MyByteSource
- 6、修改CustomerRealm
- 序列化
- RedisConfig
- RedisCache
- RedisCacheManager
- 自定义序列化MySerializeUtil
- 创建RedisConfig
- jackson自定义序列化
- MyByteSource
无序列化
1、引入Redis依赖
<!--redis整合springboot-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、配置Redis依赖
server.port=8080
server.servlet.context-path=/shiro
spring.application.name=shiro
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp
######Druid监控配置######
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/shiro?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
#dataSource Pool configuration
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.maxWait=60000
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.exceptionSorter=true
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.filters=stat,wall,log4j
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
spring.datasource.useGlobalDataSourceStat=true
mybatis.type-aliases-package=com.hz52.springboot_jsp_shiro.entity
mybatis.mapper-locations=classpath:com/hz52/mapper/*.xml
#设置调试信息
#logging.level.root=debug
logging.level.com.hz52.springboot_jsp_shiro.dao=debug
#Redis
spring.redis.port=6379
spring.redis.host=localhost
spring.redis.password=3.1415926
#设置0号数据库
spring.redis.database=0
3、创建RedisCacheManager
package com.hz52.springboot_jsp_shiro.shiro.cache;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;
/**
* @Program: springboot_jsp_shiro
* @Description: 自定义shiro缓存管理器
* @Author: 52Hz
* @CreationTime: 2021年10月23日 15:25 星期六
**/
public class RedisCacheManager implements CacheManager {
@Override
public <K, V> Cache<K, V> getCache(String cacheName) throws CacheException {
System.out.println(cacheName);
return new RedisCache<K,V>();
}
}
4、创建RedisCache
package com.hz52.springboot_jsp_shiro.shiro.cache;
import com.hz52.springboot_jsp_shiro.Utils.ApplicationContextUtils;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.util.Collection;
import java.util.Set;
/**
* @Program: springboot_jsp_shiro
* @Description: 自定义redis缓存实现
* @Author: 52Hz
* @CreationTime: 2021年10月23日 15:31 星期六
**/
public class RedisCache<k, v> implements Cache<k, v> {
@Override
public v get(k k) throws CacheException {
System.out.println("Get key:" + k);
//获取redis
RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtils.getBean("redisTemplate");
//修改序列化方式
redisTemplate.setKeySerializer(new StringRedisSerializer());
return (v) redisTemplate.opsForValue().get(k.toString());
}
@Override
public v put(k k, v v) throws CacheException {
System.out.println("Put key:" + k);
System.out.println("Put value:" + v);
//获取redis
RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtils.getBean("redisTemplate");
//修改序列化方式
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.opsForValue().set(k.toString(), v);
return null;
}
@Override
public v remove(k k) throws CacheException {
return null;
}
@Override
public void clear() throws CacheException {
}
@Override
public int size() {
return 0;
}
@Override
public Set<k> keys() {
return null;
}
@Override
public Collection<v> values() {
return null;
}
}
5、创建MyByteSource
package com.hz52.springboot_jsp_shiro.shiro.salt;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.codec.CodecSupport;
import org.apache.shiro.codec.Hex;
import org.apache.shiro.util.ByteSource;
import java.io.File;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Arrays;
/**
* @Program: springboot_jsp_shiro
* @Description:
* @Author: 52Hz
* @CreationTime: 2021年10月23日 16:49 星期六
**/
public class MyByteSource implements ByteSource, Serializable {
private byte[] bytes;
private String cachedHex;
private String cachedBase64;
public MyByteSource() {
}
public MyByteSource(byte[] bytes) {
this.bytes = bytes;
}
public MyByteSource(char[] chars) {
this.bytes = CodecSupport.toBytes(chars);
}
public MyByteSource(String string) {
this.bytes = CodecSupport.toBytes(string);
}
public MyByteSource(ByteSource source) {
this.bytes = source.getBytes();
}
public MyByteSource(File file) {
this.bytes = (new MyByteSource.BytesHelper()).getBytes(file);
}
public MyByteSource(InputStream stream) {
this.bytes = (new MyByteSource.BytesHelper()).getBytes(stream);
}
public static boolean isCompatible(Object o) {
return o instanceof byte[] || o instanceof char[] || o instanceof String || o instanceof ByteSource || o instanceof File || o instanceof InputStream;
}
@Override
public byte[] getBytes() {
return this.bytes;
}
@Override
public boolean isEmpty() {
return this.bytes == null || this.bytes.length == 0;
}
@Override
public String toHex() {
if (this.cachedHex == null) {
this.cachedHex = Hex.encodeToString(this.getBytes());
}
return this.cachedHex;
}
@Override
public String toBase64() {
if (this.cachedBase64 == null) {
this.cachedBase64 = Base64.encodeToString(this.getBytes());
}
return this.cachedBase64;
}
@Override
public String toString() {
return this.toBase64();
}
@Override
public int hashCode() {
return this.bytes != null && this.bytes.length != 0 ? Arrays.hashCode(this.bytes) : 0;
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (o instanceof ByteSource) {
ByteSource bs = (ByteSource) o;
return Arrays.equals(this.getBytes(), bs.getBytes());
} else {
return false;
}
}
private static final class BytesHelper extends CodecSupport {
private BytesHelper() {
}
public byte[] getBytes(File file) {
return this.toBytes(file);
}
public byte[] getBytes(InputStream stream) {
return this.toBytes(stream);
}
}
}
6、修改CustomerRealm
package com.hz52.springboot_jsp_shiro.shiro.realms;
import com.hz52.springboot_jsp_shiro.Utils.ApplicationContextUtils;
import com.hz52.springboot_jsp_shiro.entity.Perms;
import com.hz52.springboot_jsp_shiro.entity.User;
import com.hz52.springboot_jsp_shiro.service.UserService;
import com.hz52.springboot_jsp_shiro.shiro.salt.MyByteSource;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import java.util.List;
/**
* @Program: springboot_jsp_shiro
* @Description: 自定义realm
* @Author: 52Hz
* @CreationTime: 2021年10月20日 9:40 星期三
**/
public class CustomerRealm extends AuthorizingRealm {
//处理授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//获取身份信息
String primaryPrincipal = (String) principals.getPrimaryPrincipal();
System.out.println("调用授权认证:" + primaryPrincipal);
//根据主身份信息获取角色信息和权限信息
UserService userService = (UserService) ApplicationContextUtils.getBean("userService");
User user = userService.findRolesByUserName(primaryPrincipal);
//授权角色信息
if (!CollectionUtils.isEmpty(user.getRoles())) {
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
user.getRoles().forEach(role -> {
//角色信息
simpleAuthorizationInfo.addRole(role.getName());
//权限信息
List<Perms> perms = userService.findPermsByRid(role.getId());
if (!CollectionUtils.isEmpty(perms)) {
perms.forEach(perm -> {
simpleAuthorizationInfo.addStringPermission(perm.getName());
});
}
});
return simpleAuthorizationInfo;
}
return null;
}
//处理认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String principal = (String) token.getPrincipal();
//在工厂中 获取service对象
UserService userService = (UserService) ApplicationContextUtils.getBean("userService");
User user = userService.findByUserName(principal);
if (!ObjectUtils.isEmpty(user)) {
return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(),
new MyByteSource(user.getSalt()),
//ByteSource.Util.bytes(user.getSalt()),
this.getName());
}
return null;
}
}
序列化
RedisConfig
package com.hz52.springboot_jsp_shiro.config;
import com.hz52.springboot_jsp_shiro.Utils.MySerializeUtil;
import org.springframework.context.annotation.Bean;
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.StringRedisSerializer;
import java.net.UnknownHostException;
/**
* @Program: springboot_jsp_shiro
* @Description:
* @Author: 52Hz
* @CreationTime: 2021年11月02日 13:26 星期二
**/
@Configuration
public class RedisConfig {
//自定义一个redisTemplate,固定模板,可以直接使用
@Bean
@SuppressWarnings("all")
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory)
throws UnknownHostException {
//为了开发方便,采用<String,Object>
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
//String的序列化
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
//key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
//hash的key采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
//value序列化方式采用jackson
template.setValueSerializer(new MySerializeUtil());
//hash的value采用...的序列化方式
template.setHashValueSerializer(new MySerializeUtil());
template.afterPropertiesSet();
return template;
}
}
RedisCache
package com.hz52.springboot_jsp_shiro.shiro.cache;
import com.hz52.springboot_jsp_shiro.Utils.ApplicationContextUtils;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.springframework.data.redis.core.RedisTemplate;
import java.util.Collection;
import java.util.Set;
/**
* @Program: springboot_jsp_shiro
* @Description: 自定义redis缓存实现
* @Author: 52Hz
* @CreationTime: 2021年10月23日 15:31 星期六
**/
public class RedisCache<k, v> implements Cache<k, v> {
private String cacheName;
public RedisCache() {
}
public RedisCache(String cacheName) {
this.cacheName = cacheName;
}
@Override
public v get(k k) throws CacheException {
System.out.println("Get key:" + k.toString());
return (v) getRedisTemplate().opsForHash().get(this.cacheName, k.toString());
}
@Override
public v put(k k, v v) throws CacheException {
System.out.println("Put key:" + k);
System.out.println("Put value:" + v);
getRedisTemplate().opsForHash().put(this.cacheName, k.toString(), v);
return null;
}
@Override
public v remove(k k) throws CacheException {
return (v) getRedisTemplate().opsForHash().delete(this.cacheName, k.toString());
}
@Override
public void clear() throws CacheException {
getRedisTemplate().opsForHash().delete(this.cacheName);
}
@Override
public int size() {
return getRedisTemplate().opsForHash().size(this.cacheName).intValue();
}
@Override
public Set<k> keys() {
return getRedisTemplate().opsForHash().keys(this.cacheName);
}
@Override
public Collection<v> values() {
return getRedisTemplate().opsForHash().values(this.cacheName);
}
private RedisTemplate getRedisTemplate() {
RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtils.getBean("redisTemplate");
return redisTemplate;
}
}
RedisCacheManager
package com.hz52.springboot_jsp_shiro.shiro.cache;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;
/**
* @Program: springboot_jsp_shiro
* @Description:
* @Author: 52Hz
* @CreationTime: 2021年11月02日 11:05 星期二
**/
public class RedisCacheManager implements CacheManager {
@Override
public <K, V> Cache<K, V> getCache(String cacheName) throws CacheException {
System.out.println(cacheName);
return new RedisCache<K,V>(cacheName);
}
}
自定义序列化MySerializeUtil
package com.hz52.springboot_jsp_shiro.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import java.io.*;
/**
* @author: wangsaichao
* @date: 2018/6/20
* @description: redis的value序列化工具
*/
public class MySerializeUtil implements RedisSerializer {
private static Logger logger = LoggerFactory.getLogger(MySerializeUtil.class);
public static boolean isEmpty(byte[] data) {
return (data == null || data.length == 0);
}
/**
* 序列化为字节数组
*
*/
@Override
public byte[] serialize(Object object) throws SerializationException {
byte[] result = null;
if (object == null) {
return new byte[0];
}
try (
ByteArrayOutputStream byteStream = new ByteArrayOutputStream(128);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteStream)
){
if (!(object instanceof Serializable)) {
throw new IllegalArgumentException(MySerializeUtil.class.getSimpleName() + " requires a Serializable payload " +
"but received an object of type [" + object.getClass().getName() + "]");
}
objectOutputStream.writeObject(object);
objectOutputStream.flush();
result = byteStream.toByteArray();
} catch (Exception ex) {
logger.error("Failed to serialize",ex);
}
return result;
}
/**
* 反序列化
* @param bytes
* @return
* @throws SerializationException
*/
@Override
public Object deserialize(byte[] bytes) throws SerializationException {
Object result = null;
if (isEmpty(bytes)) {
return null;
}
try (
ByteArrayInputStream byteStream = new ByteArrayInputStream(bytes);
ObjectInputStream objectInputStream = new ObjectInputStream(byteStream)
){
result = objectInputStream.readObject();
} catch (Exception e) {
logger.error("Failed to deserialize",e);
}
return result;
}
}
创建RedisConfig
package com.hz52.springboot_jsp_shiro.config;
import com.hz52.springboot_jsp_shiro.Utils.MySerializeUtil;
import org.springframework.context.annotation.Bean;
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.StringRedisSerializer;
import java.net.UnknownHostException;
/**
* @Program: springboot_jsp_shiro
* @Description:
* @Author: 52Hz
* @CreationTime: 2021年11月02日 13:26 星期二
**/
@Configuration
public class RedisConfig {
//自定义一个redisTemplate,固定模板,可以直接使用
@Bean
@SuppressWarnings("all")
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory)
throws UnknownHostException {
//为了开发方便,采用<String,Object>
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
//String的序列化
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
//key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
//hash的key采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
//value序列化方式采用jackson
template.setValueSerializer(new MySerializeUtil());
//hash的value采用...的序列化方式
template.setHashValueSerializer(new MySerializeUtil());
template.afterPropertiesSet();
return template;
}
}
jackson自定义序列化
//package com.hz52.springboot_jsp_shiro.Utils;
//
//import org.springframework.data.redis.serializer.RedisSerializer;
//import org.springframework.data.redis.serializer.SerializationException;
//
//import java.nio.charset.Charset;
//
///**
// * @Program: springboot_jsp_shiro
// * @Description:
// * @Author: 52Hz
// * @CreationTime: 2021年11月02日 13:38 星期二
// **/
//public class JacksonRedisSerializer<T> implements RedisSerializer {
//
//
// public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
//
// private Class<T> clazz;
//
// public JacksonRedisSerializer(Class<T> clazz) {
// super();
// this.clazz = clazz;
// }
//
// @Override
// public byte[] serialize(Object o) throws SerializationException {
// if (o == null) {
// return new byte[0];
// }
// try {
// return JsonUtil.obj2json(o).getBytes();
// } catch (Exception e) {
// e.printStackTrace();
// }
// return new byte[0];
// }
// @Override
// public T deserialize(byte[] bytes) throws SerializationException {
// if (bytes == null || bytes.length <= 0) {
// return null;
// }
// String str = new String(bytes, DEFAULT_CHARSET);
// try {
// return JsonUtil.json2pojo(str,clazz);
// } catch (Exception e) {
// e.printStackTrace();
// }
// return null;
// }
//}
MyByteSource
package com.hz52.springboot_jsp_shiro.shiro.salt;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.codec.CodecSupport;
import org.apache.shiro.codec.Hex;
import org.apache.shiro.util.ByteSource;
import java.io.File;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Arrays;
/**
* @Program: springboot_jsp_shiro
* @Description:
* @Author: 52Hz
* @CreationTime: 2021年10月23日 16:49 星期六
**/
public class MyByteSource implements ByteSource, Serializable {
private byte[] bytes;
private String cachedHex;
private String cachedBase64;
public MyByteSource() {
}
public MyByteSource(byte[] bytes) {
this.bytes = bytes;
}
public MyByteSource(char[] chars) {
this.bytes = CodecSupport.toBytes(chars);
}
public MyByteSource(String string) {
this.bytes = CodecSupport.toBytes(string);
}
public MyByteSource(ByteSource source) {
this.bytes = source.getBytes();
}
public MyByteSource(File file) {
this.bytes = (new MyByteSource.BytesHelper()).getBytes(file);
}
public MyByteSource(InputStream stream) {
this.bytes = (new MyByteSource.BytesHelper()).getBytes(stream);
}
public static boolean isCompatible(Object o) {
return o instanceof byte[] || o instanceof char[] || o instanceof String || o instanceof ByteSource || o instanceof File || o instanceof InputStream;
}
@Override
public byte[] getBytes() {
return this.bytes;
}
@Override
public boolean isEmpty() {
return this.bytes == null || this.bytes.length == 0;
}
@Override
public String toHex() {
if (this.cachedHex == null) {
this.cachedHex = Hex.encodeToString(this.getBytes());
}
return this.cachedHex;
}
@Override
public String toBase64() {
if (this.cachedBase64 == null) {
this.cachedBase64 = Base64.encodeToString(this.getBytes());
}
return this.cachedBase64;
}
@Override
public String toString() {
return this.toBase64();
}
@Override
public int hashCode() {
return this.bytes != null && this.bytes.length != 0 ? Arrays.hashCode(this.bytes) : 0;
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (o instanceof ByteSource) {
ByteSource bs = (ByteSource) o;
return Arrays.equals(this.getBytes(), bs.getBytes());
} else {
return false;
}
}
private static final class BytesHelper extends CodecSupport {
private BytesHelper() {
}
public byte[] getBytes(File file) {
return this.toBytes(file);
}
public byte[] getBytes(InputStream stream) {
return this.toBytes(stream);
}
}
}
这篇关于八、springboot缓存之Redis的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!