栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

八、springboot缓存之Redis

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

八、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依赖
 
        
            org.springframework.boot
            spring-boot-starter-data-redis
        
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
public class RedisCacheManager implements CacheManager {
    
    @Override
    public  Cache getCache(String cacheName) throws CacheException {
        System.out.println(cacheName);
        
        return new RedisCache();
    }
}

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;


public class RedisCache implements Cache {

    @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 keys() {
        return null;
    }

    @Override
    public Collection 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;


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;


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 = 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;


@Configuration
public class RedisConfig  {
    //自定义一个redisTemplate,固定模板,可以直接使用
    @Bean
    @SuppressWarnings("all")
    public RedisTemplate redisTemplate(RedisConnectionFactory factory)
            throws UnknownHostException {
        //为了开发方便,采用
        RedisTemplate 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;


public class RedisCache implements Cache {

    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 keys() {
        return getRedisTemplate().opsForHash().keys(this.cacheName);
    }

    @Override
    public Collection 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;

public class RedisCacheManager implements CacheManager {

    @Override
    public  Cache getCache(String cacheName) throws CacheException {
        System.out.println(cacheName);

        return new RedisCache(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.*;



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;
    }

    
    @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;


@Configuration
public class RedisConfig  {
    //自定义一个redisTemplate,固定模板,可以直接使用
    @Bean
    @SuppressWarnings("all")
    public RedisTemplate redisTemplate(RedisConnectionFactory factory)
            throws UnknownHostException {
        //为了开发方便,采用
        RedisTemplate 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;
//
//
//public class JacksonRedisSerializer implements RedisSerializer {
//
//
//    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
//
//    private Class clazz;
//
//    public JacksonRedisSerializer(Class 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;


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);
        }
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/434589.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号