怎样用dw做网站导航条,北京健康宝优化,网站首页设计报价多少,新手网站设计看哪本书1.安装redis#xff0c;并配置密码
这里就不针对于redis的安装约配置进行说明了#xff0c;直接在项目中使用。
redis在windows环境下安装#xff1a;Window下Redis的安装和部署详细图文教程#xff08;Redis的安装和可视化工具的使用#xff09;_redis安装-CSDN博客
2…1.安装redis并配置密码
这里就不针对于redis的安装约配置进行说明了直接在项目中使用。
redis在windows环境下安装Window下Redis的安装和部署详细图文教程Redis的安装和可视化工具的使用_redis安装-CSDN博客
2.pom.xml文件中引入需要的maven dependencygroupIdredis.clients/groupIdartifactIdjedis/artifactIdversion2.9.0/version/dependency3.在项目的配置文件中加入redis的配置
redis:database: 0host: localhostpassword: 123456pool:max-active: 8max-idle: 8max-wait: -1min-idle: 0port: 6379timeout: 30004.添加redis的配置文件放在项目的config文件夹下
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;/*** author kjz*/
Configuration
EnableCaching
public class RedisConfig extends CachingConfigurerSupport {Value(${redis.host})private String host;Value(${redis.port})private int port;Value(${redis.timeout})private int timeout;Value(${redis.pool.max-idle})private int maxIdle;Value(${redis.pool.max-wait})private long maxWaitMillis;Value(${redis.password})private String password;Beanpublic JedisPool redisPoolFactory() {JedisPoolConfig jedisPoolConfig new JedisPoolConfig();jedisPoolConfig.setMaxIdle(maxIdle);jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);JedisPool jedisPool new JedisPool(jedisPoolConfig, host, port, timeout);return jedisPool;}Beanpublic RedisConnectionFactory redisConnectionFactory() {JedisPoolConfig jedisPoolConfig new JedisPoolConfig();jedisPoolConfig.setMaxIdle(maxIdle);jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);JedisConnectionFactory jedisConnectionFactory new JedisConnectionFactory(jedisPoolConfig);jedisConnectionFactory.setHostName(host);jedisConnectionFactory.setPort(port);jedisConnectionFactory.setTimeout(timeout);jedisConnectionFactory.setPassword(password);return jedisConnectionFactory;}}5.具体实现思路手动实现
实现思路
创建一个过滤器拦截除了登录之外的所有请求判断请求中是否存在cookie如果存在cookie则判断redis中是否存在以cookie为key的键值对数据如果有则取出对应的value同时对这个key的过期时间进行续期如果没有则返回一个响应说明登录已经过期了将Value就是session进行Jason反序列化得到session对象然后把Session绑定到当前的请求中如果不存在cookie则直接返回一个响应说明还未登录。如果是登录请求的话直接到controller中进行登录校验让深沉的session通过json序列化放到redis中并且以uuid为key同时返回给前端一个cookie字段cookie字段的值就是uuid请求完成之后在过滤器中将会话数据session更新到redis中。
下面是思路流程图 代码实现
创建过滤器 SessionFilter
import com.fasterxml.jackson.databind.ObjectMapper;
import redis.clients.jedis.Jedis;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;public class SessionFilter implements Filter {private JedisPool jedisPool;private ObjectMapper objectMapper;private static final String LOGIN_PATH /login;private static final int SESSION_EXPIRATION_TIME 30 * 60; // 30 minutes in secondspublic SessionFilter(JedisPool jedisPool) {this.jedisPool jedisPool;this.objectMapper new ObjectMapper();}Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws IOException, ServletException {HttpServletRequest httpRequest (HttpServletRequest) request;HttpServletResponse httpResponse (HttpServletResponse) response;String requestUri httpRequest.getRequestURI();if (requestUri.equals(LOGIN_PATH)) {// 直接转发到登录控制器chain.doFilter(request, response);} else {// 检查 CookieCookie[] cookies httpRequest.getCookies();String sessionId null;if (cookies ! null) {for (Cookie cookie : cookies) {if (SESSIONID.equals(cookie.getName())) {sessionId cookie.getValue();break;}}}if (sessionId ! null) {try (Jedis jedis jedisPool.getResource()) {String sessionDataJson jedis.get(sessionId);if (sessionDataJson ! null) {// 续期jedis.expire(sessionId, SESSION_EXPIRATION_TIME);// 反序列化 SessionMapString, Object sessionAttributes objectMapper.readValue(sessionDataJson, Map.class);HttpSessionWrapper wrappedSession new HttpSessionWrapper(sessionAttributes);request.setAttribute(httpSession, wrappedSession);// 继续执行过滤器链chain.doFilter(request, response);// 更新 Session 到 Redisif (wrappedSession.isDirty()) {jedis.set(sessionId, objectMapper.writeValueAsString(wrappedSession.getSessionData()));}} else {// 登录过期httpResponse.setContentType(application/json);httpResponse.getWriter().write({\error\: \Session expired\});}} catch (Exception e) {// 处理异常e.printStackTrace();httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);}} else {// 未登录httpResponse.setContentType(application/json);httpResponse.getWriter().write({\error\: \Not logged in\});}}}// ... 其他 Filter 方法 ...
}注册过滤器
在 Spring 配置中注册过滤器
Bean
public FilterRegistrationBeanSessionFilter sessionFilterRegistration(SessionFilter sessionFilter) {FilterRegistrationBeanSessionFilter registrationBean new FilterRegistrationBean();registrationBean.setFilter(sessionFilter);registrationBean.addUrlPatterns(/*);return registrationBean;
}创建 HttpSessionWrapper 类
将session和sessionid封装到这个类里面
import javax.servlet.http.HttpSession;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;public class HttpSessionWrapper implements HttpSession {private final MapString, Object attributes;private boolean dirty;public HttpSessionWrapper(MapString, Object attributes) {this.attributes attributes;this.dirty false;}// ... 实现 HttpSession 接口的方法 ...public void setAttribute(String name, Object value) {attributes.put(name, value);dirty true;}public MapString, Object getSessionData() {return attributes;}public boolean isDirty() {return dirty;}// ... 其他方法 ...
}登录控制器
RestController
public class LoginController {PostMapping(/login)public HttpServletResponse login(HttpServletRequest request, HttpServletResponse response) {// ... 登录逻辑 ...// 创建新的会话String sessionId UUID.randomUUID().toString();MapString, Object sessionAttributes new HashMap();// 填充会话属性sessionAttributes.put(user, user);// 使用 JsonUtil 序列化会话并存储到 RedisString sessionDataJson JsonUtil.obj2String(sessionAttributes);try (Jedis jedis jedisPool.getResource()) {jedis.setex(sessionId, SESSION_EXPIRATION_TIME, sessionDataJson);} catch (Exception e) {// 处理异常e.printStackTrace();return Error;}// 创建 Cookie 并设置给客户端Cookie sessionCookie new Cookie(SESSIONID, sessionId);sessionCookie.setPath(/);sessionCookie.setHttpOnly(true); // 确保 Cookie 不会被 JavaScript 访问sessionCookie.setSecure(true); // 确保 Cookie 在 HTTPS 连接中传输response.addCookie(sessionCookie);return HttpServletResponse ;}
}下面是序列化工具类
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;/***author kjz*/
Slf4j
public class JsonUtil {private static ObjectMapper objectMapper new ObjectMapper();static{//对象的所有字段全部列入objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);}public static T String obj2String(T obj){if(obj null){return null;}try {return obj instanceof String ? (String)obj : objectMapper.writeValueAsString(obj);} catch (Exception e) {log.warn(Parse Object to String error,e);return null;}}/*** 格式化json串看起来比较好看但是有换行符等符号会比没有格式化的大* param obj* param T* return*/public static T String obj2StringPretty(T obj){if(obj null){return null;}try {return obj instanceof String ? (String)obj : objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);} catch (Exception e) {log.warn(Parse Object to String error,e);return null;}}public static T T string2Obj(String str,ClassT clazz){if(StringUtils.isEmpty(str) || clazz null){return null;}try {return clazz.equals(String.class)? (T)str : objectMapper.readValue(str,clazz);} catch (Exception e) {log.warn(Parse String to Object error,e);return null;}}public static T T string2Obj(String str, TypeReferenceT typeReference){if(StringUtils.isEmpty(str) || typeReference null){return null;}try {return (T)(typeReference.getType().equals(String.class)? str : objectMapper.readValue(str,typeReference));} catch (Exception e) {log.warn(Parse String to Object error,e);return null;}}/*** 转换集合* ListUser/* param str* param collectionClass* param elementClasses* param T* return*/public static T T string2Obj(String str,Class? collectionClass,Class?... elementClasses){JavaType javaType objectMapper.getTypeFactory().constructParametricType(collectionClass,elementClasses);try {return objectMapper.readValue(str,javaType);} catch (Exception e) {log.warn(Parse String to Object error,e);return null;}}
}6.利用Spring Session Data Redis框架实现 引入Spring Session Data Redis 的依赖 dependencygroupIdorg.springframework.session/groupIdartifactIdspring-session-data-redis/artifactIdversion2.7.0/version/dependency
创建Spring Session的配置类
创建一个配置类 SessionConfig使用 EnableRedisHttpSession 注解来启用 Spring Session 的 Redis 支持
import org.springframework.session.data.redis.config.ConfigureRedisAction;
import org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;Configuration
EnableRedisHttpSession
public class SessionConfig {// 配置会话过期时间例如设置为 1800 秒即 30 分钟Beanpublic RedisHttpSessionConfiguration redisHttpSessionConfiguration() {RedisHttpSessionConfiguration configuration new RedisHttpSessionConfiguration();configuration.setMaxInactiveIntervalInSeconds(1800);return configuration;}// 如果你使用的是 Spring Boot 2.3 或更高版本你可能需要定义这个 Bean 来避免警告Beanpublic static ConfigureRedisAction configureRedisAction() {return ConfigureRedisAction.NO_OP;}
}EnableRedisHttpSession 是一个方便的注解它做了以下几件事情
启用 Spring Session 的支持使得 HttpSession 能够被 Spring Session 管理。配置 Redis 作为会话数据的存储后端。注册一个 SessionRepositoryFilter 的 Bean这个 Filter 负责拦截请求并将标准的 HttpSession 替换为 Spring Session 的实现。
Session的创建存储和获取
做完上面的配置之后你可以像使用常规 HttpSession 一样使用 Spring Session。每次修改会话时Spring Session 都会自动将这些更改同步到 Redis。
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpSession;RestController
public class SessionController {GetMapping(/setSession)public String setSession(HttpSession session) {session.setAttribute(message, Hello, Redis Session!);return Session set in Redis;}GetMapping(/getSession)public String getSession(HttpSession session) {return Session message: session.getAttribute(message);}
} 文章转载自: http://www.morning.hxycm.cn.gov.cn.hxycm.cn http://www.morning.rzrbw.cn.gov.cn.rzrbw.cn http://www.morning.hqbk.cn.gov.cn.hqbk.cn http://www.morning.jsrnf.cn.gov.cn.jsrnf.cn http://www.morning.rqjxc.cn.gov.cn.rqjxc.cn http://www.morning.lfmwt.cn.gov.cn.lfmwt.cn http://www.morning.ssjry.cn.gov.cn.ssjry.cn http://www.morning.jzfxk.cn.gov.cn.jzfxk.cn http://www.morning.srwny.cn.gov.cn.srwny.cn http://www.morning.tqbyw.cn.gov.cn.tqbyw.cn http://www.morning.mymz.cn.gov.cn.mymz.cn http://www.morning.mbprq.cn.gov.cn.mbprq.cn http://www.morning.lzttq.cn.gov.cn.lzttq.cn http://www.morning.qcdtzk.cn.gov.cn.qcdtzk.cn http://www.morning.jmtrq.cn.gov.cn.jmtrq.cn http://www.morning.mgnrc.cn.gov.cn.mgnrc.cn http://www.morning.bswhr.cn.gov.cn.bswhr.cn http://www.morning.hmdyl.cn.gov.cn.hmdyl.cn http://www.morning.wjhqd.cn.gov.cn.wjhqd.cn http://www.morning.w58hje.cn.gov.cn.w58hje.cn http://www.morning.njqpg.cn.gov.cn.njqpg.cn http://www.morning.qkrz.cn.gov.cn.qkrz.cn http://www.morning.zfhwm.cn.gov.cn.zfhwm.cn http://www.morning.dmhs.cn.gov.cn.dmhs.cn http://www.morning.qnqt.cn.gov.cn.qnqt.cn http://www.morning.nppml.cn.gov.cn.nppml.cn http://www.morning.bntfy.cn.gov.cn.bntfy.cn http://www.morning.mwwnz.cn.gov.cn.mwwnz.cn http://www.morning.pdbgm.cn.gov.cn.pdbgm.cn http://www.morning.cpnlq.cn.gov.cn.cpnlq.cn http://www.morning.qcbhb.cn.gov.cn.qcbhb.cn http://www.morning.wfwqr.cn.gov.cn.wfwqr.cn http://www.morning.wmdlp.cn.gov.cn.wmdlp.cn http://www.morning.kaweilu.com.gov.cn.kaweilu.com http://www.morning.lgsqy.cn.gov.cn.lgsqy.cn http://www.morning.nlrp.cn.gov.cn.nlrp.cn http://www.morning.fyglr.cn.gov.cn.fyglr.cn http://www.morning.rnnq.cn.gov.cn.rnnq.cn http://www.morning.yxzfl.cn.gov.cn.yxzfl.cn http://www.morning.wpqwk.cn.gov.cn.wpqwk.cn http://www.morning.dwmtk.cn.gov.cn.dwmtk.cn http://www.morning.ypxyl.cn.gov.cn.ypxyl.cn http://www.morning.tnzwm.cn.gov.cn.tnzwm.cn http://www.morning.skfkx.cn.gov.cn.skfkx.cn http://www.morning.cwcdr.cn.gov.cn.cwcdr.cn http://www.morning.zcfmb.cn.gov.cn.zcfmb.cn http://www.morning.lsjtq.cn.gov.cn.lsjtq.cn http://www.morning.ymwny.cn.gov.cn.ymwny.cn http://www.morning.wqnc.cn.gov.cn.wqnc.cn http://www.morning.wfcqr.cn.gov.cn.wfcqr.cn http://www.morning.dshxj.cn.gov.cn.dshxj.cn http://www.morning.amlutsp.cn.gov.cn.amlutsp.cn http://www.morning.sqqhd.cn.gov.cn.sqqhd.cn http://www.morning.jgcxh.cn.gov.cn.jgcxh.cn http://www.morning.nnwmd.cn.gov.cn.nnwmd.cn http://www.morning.brwei.com.gov.cn.brwei.com http://www.morning.zwdrz.cn.gov.cn.zwdrz.cn http://www.morning.wlqbr.cn.gov.cn.wlqbr.cn http://www.morning.rfdqr.cn.gov.cn.rfdqr.cn http://www.morning.duckgpt.cn.gov.cn.duckgpt.cn http://www.morning.zlmbc.cn.gov.cn.zlmbc.cn http://www.morning.xsctd.cn.gov.cn.xsctd.cn http://www.morning.xmttd.cn.gov.cn.xmttd.cn http://www.morning.tyjnr.cn.gov.cn.tyjnr.cn http://www.morning.zkjqj.cn.gov.cn.zkjqj.cn http://www.morning.nkyc.cn.gov.cn.nkyc.cn http://www.morning.wqkzf.cn.gov.cn.wqkzf.cn http://www.morning.tmcmj.cn.gov.cn.tmcmj.cn http://www.morning.rjrlx.cn.gov.cn.rjrlx.cn http://www.morning.bnqcm.cn.gov.cn.bnqcm.cn http://www.morning.ghxtk.cn.gov.cn.ghxtk.cn http://www.morning.bnfrj.cn.gov.cn.bnfrj.cn http://www.morning.bmts.cn.gov.cn.bmts.cn http://www.morning.lqzhj.cn.gov.cn.lqzhj.cn http://www.morning.nzfqw.cn.gov.cn.nzfqw.cn http://www.morning.sqskm.cn.gov.cn.sqskm.cn http://www.morning.yrfxb.cn.gov.cn.yrfxb.cn http://www.morning.wmqrn.cn.gov.cn.wmqrn.cn http://www.morning.xhftj.cn.gov.cn.xhftj.cn http://www.morning.qjxxc.cn.gov.cn.qjxxc.cn