10月8日spring学习笔记

标签

spring

springboot

token

Authorization

redis

发布时间:

本文字数:883 字 阅读完需:约 5 分钟

token 用户登录

alt

存入redis

Vo对象必须实现Serializable序列化接口

application.xml

# Spring配置
spring:
  # redis配置  
  redis: 
     # 地址
     host: 127.0.0.1
     # 端口,默认为6379
     port: 6379 
     # 连接超时时间
     timeout: 10s
     lettuce:
      pool:
        # 连接池中的最小空闲连接
        min-idle: 0
        # 连接池中的最大空闲连接
        max-idle: 8
        # 连接池的最大数据库连接数
        max-active: 8
        # #连接池最大阻塞等待时间(使用负值表示没有限制)
        max-wait: -1m

RedisUtil工具类

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
**
 * 缓存操作类
 */
@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 写入缓存
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
            throw  e;
        }
        return result;
    }

    /**
     * 写入缓存设置时效时间
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value, Long expireTime, TimeUnit timeUnit) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, expireTime, timeUnit);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 批量删除对应的value
     *
     * @param keys
     */
    public void remove(final String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }

    /**
     * 批量删除key
     *
     * @param pattern
     */
    public void removePattern(final String pattern) {
        Set<Serializable> keys = redisTemplate.keys(pattern);
        if (keys.size() > 0) {
            redisTemplate.delete(keys);
        }
    }

    /**
     * 删除对应的value
     *
     * @param key
     */
    public void remove(final String key) {
        if (exists(key)) {
            redisTemplate.delete(key);
        }
    }

    /**
     * 判断缓存中是否有对应的value
     *
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 读取缓存
     *
     * @param key
     * @return
     */
    public Object get(final String key) {
        Object result = null;
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        result = operations.get(key);
        return result;
    }

    /**
     * 哈希 添加
     *
     * @param key
     * @param hashKey
     * @param value
     */
    public void hmSet(String key, Object hashKey, Object value) {
        HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
        hash.put(key, hashKey, value);
    }

    /**
     * 哈希获取数据
     *
     * @param key
     * @param hashKey
     * @return
     */
    public Object hmGet(String key, Object hashKey) {
        HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
        return hash.get(key, hashKey);
    }

    /**
     * 列表添加
     *
     * @param k
     * @param v
     */
    public void lPush(String k, Object v) {
        ListOperations<String, Object> list = redisTemplate.opsForList();
        list.rightPush(k, v);
    }

    /**
     * 列表获取
     *
     * @param k
     * @param l
     * @param l1
     * @return
     */
    public List<Object> lRange(String k, long l, long l1) {
        ListOperations<String, Object> list = redisTemplate.opsForList();
        return list.range(k, l, l1);
    }

    /**
     * 集合添加
     *
     * @param key
     * @param value
     */
    public void add(String key, Object value) {
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        set.add(key, value);
    }

    /**
     * 集合获取
     *
     * @param key
     * @return
     */
    public Set<Object> setMembers(String key) {
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        return set.members(key);
    }

    /**
     * 有序集合添加
     *
     * @param key
     * @param value
     * @param scoure
     */
    public void zAdd(String key, Object value, double scoure) {
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        zset.add(key, value, scoure);
    }

    /**
     * 有序集合获取
     *
     * @param key
     * @param scoure
     * @param scoure1
     * @return
     */
    public Set<Object> rangeByScore(String key, double scoure, double scoure1) {
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        return zset.rangeByScore(key, scoure, scoure1);
    }
}

工具类调用

使用redisUtil.getset即可

@Autowired
    private RedisUtil redisUtil;
    @PostMapping("/login")
    public AjaxResult login(@RequestBody SysUser sysUser){
        SysUser user = sysUserService.login(sysUser);
        AjaxResult ajaxResult = null;
        if(user != null) {
            Map<String, Object> objectMap = new HashMap<>();
            objectMap.put("loginUserName",user.getUserName());
            objectMap.put("headImgUrl",sysUserService.getHeadImgUrl(user.getImgUrl()));
            String token =  UUID.randomUUID().toString();
            objectMap.put("token", token);
            //token存入redis
            redisUtil.set(token, user, 15L, TimeUnit.MINUTES);
            ajaxResult = AjaxResult.success(200,"登录成功", objectMap);
        }else{
            ajaxResult = AjaxResult.fail(200,"账号或密码错误", null);
        }
         return ajaxResult;
    }

后端处理

拦截器配置类

WebConfig.java

package com.zr.config;

import javax.annotation.Resource;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.zr.interceptor.AuthorizationInterceptor;

// @Configuration
public class WebConfig implements WebMvcConfigurer{

    @Resource
    private AuthorizationInterceptor authorizationInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration interceptorRegistration = registry.addInterceptor(authorizationInterceptor);
        interceptorRegistration.addPathPatterns("/**").excludePathPatterns("/sys/user/login");
    }
    
}

AuthorizationInterceptor.java

package com.zr.interceptor;

import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import com.alibaba.fastjson.JSON;
import com.zr.utils.AjaxResult;
import com.zr.utils.RedisUtil;

@Component
public class AuthorizationInterceptor implements HandlerInterceptor{
    @Resource
    private RedisUtil redisUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String token = request.getHeader("Authorization");
        if(!StringUtils.hasLength(token)||redisUtil.get(token) == null){
            //返回JSON
            AjaxResult ajaxResult = AjaxResult.fail(401, "用户未登录", null);
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.write(JSON.toJSONString(ajaxResult));
            out.flush();
            out.close();
            return false;
        }
        else{
            //更新过期时间
            redisUtil.set(token, redisUtil.get(token), 15L, TimeUnit.MINUTES);
        }
        return true;

    }
    
}

前端处理

main.js中添加拦截器即可

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import axios from "axios"
import store from "./store";
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';

Vue.config.productionTip = false
//设置axios为Vue的属性$axios
Vue.prototype.$axios = axios
Vue.use(ElementUI);

// 在封装axios的文件中添加拦截器
// 添加请求拦截器,在请求头中加token
axios.interceptors.request.use(
  config => {
    config.headers.Authorization = store.state.token;
    return config
  },
  error => {
    return Promise.reject(error)
  })

//添加全局响应拦截器
axios.interceptors.response.use(
  resp =>{
    if(resp.data.code == 401){
      store.state.token = '';
      router.push('Login').then();
    }
    return resp;
  },
  error =>{
    return Promise.reject(error)
  }
)
/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})

springboot自定义配置文件

注解 @Value("${img.path}") 中的img.path对应配置文件的

application.yaml

img:
  path: D:\\Img\\