Spring Boot—19Session
pom.xm
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
application.properties
#
server.address=0.0.0.0
server.port=8080
server.servlet.context-path=/test
server.session.timeout=300
server.error.path=/error
#
server.tomcat.accesslog.enabled=true
server.tomcat.accesslog.buffered=true
server.tomcat.accesslog.directory=D:/Project/JavaWeb/SpringBoot/04JPASpringBoot/logs
#
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=Asia/Shanghai
#
spring.thymeleaf.cache=true
spring.thymeleaf.enabled=true file.upload.path=D:/Project/JavaWeb/SpringBoot/04JPASpringBoot/fileUpLoad spring.servlet.multipart.enabled=true
spring.servlet.multipart.file-size-threshold=0
spring.servlet.multipart.location=D:/Project/JavaWeb/SpringBoot/04JPASpringBoot/temp
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
spring.servlet.multipart.resolve-lazily=false spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.one.url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.druid.one.username=root
spring.datasource.druid.one.password=gis
spring.datasource.druid.one.driver-class-name=com.mysql.cj.jdbc.Driver ##Druid
spring.datasource.druid.one.initial-size=2
spring.datasource.druid.one.max-active=5
spring.datasource.druid.one.min-idle=1
spring.datasource.druid.one.max-wait=60000
spring.datasource.druid.one.pool-prepared-statements=true
spring.datasource.druid.one.max-pool-prepared-statement-per-connection-size=20
spring.datasource.druid.one.validation-query=SELECT 1 FROM DUAL
spring.datasource.druid.one.validation-query-timeout=60000
spring.datasource.druid.one.test-on-borrow=false
spring.datasource.druid.one.test-on-return=false
spring.datasource.druid.one.test-while-idle=true
spring.datasource.druid.one.time-between-eviction-runs-millis=60000
spring.datasource.druid.one.min-evictable-idle-time-millis=100000
#spring.datasource.druid.one.max-evictable-idle-time-millis=
spring.datasource.druid.one.filters=stat,wall,log
spring.datasource.druid.one.logSlowSql=true #
# debug=true # Enable debug logs.
# trace=true # Enable trace logs. # LOGGING
logging.config=classpath:logback.xml spring.redis.host=127.0.0.1
spring.redis.password=gis
spring.redis.port=6379
spring.redis.pool.max-active=8
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-idle=8
spring.redis.jedis.pool.max-wait=-1ms
spring.redis.jedis.pool.min-idle=0
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.max-wait=-1ms
spring.redis.lettuce.pool.min-idle=0
spring.redis.lettuce.shutdown-timeout=100ms
spring.redis.ssl=false
spring.redis.timeout=5000 redis.message.topic=spring.news.* # Cache
spring.cache.type=Redis
spring.cache.redis.cache-null-values=true
spring.cache.redis.key-prefix=spring:cache:
spring.cache.redis.time-to-live=0ms
spring.cache.redis.use-key-prefix=true # Session
spring.session.store-type=Redis
spring.session.redis.flush-mode=IMMEDIATE
Redis的Session配置类RedisSessionManagerConfiguration,主要是实现JSON格式的系列化
package com.smartmap.sample.test.conf; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer; @Configuration
public class RedisSessionManagerConfiguration {
// 设置Session的系列化为JSON格式
@Bean(name = "springSessionDefaultRedisSerializer")
public RedisSerializer<?> getRedisSerializer() {
return new GenericJackson2JsonRedisSerializer();
}
}
RedisTemplate的配置
package com.smartmap.sample.test.conf; 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.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer; @Configuration
public class RedisConfiguration { @Bean
public RedisTemplate<String, Object> stringJsonRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(redisConnectionFactory);
template.setDefaultSerializer(new GenericJackson2JsonRedisSerializer());
RedisSerializer<String> stringSerializer = new StringRedisSerializer();
template.setKeySerializer(stringSerializer);
template.setHashKeySerializer(stringSerializer);
return template;
} }
Redis缓存配置RedisCacheManagerCustomizer
package com.smartmap.sample.test.conf; import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheManager.RedisCacheManagerBuilder;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializationContext.SerializationPair;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer; import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper; @Configuration
public class RedisCacheManagerCustomizer { @Value("${spring.cache.redis.key-prefix}")
private String keyPrefix; @Bean
public RedisCacheConfiguration redisCacheConfiguration() {
GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
return RedisCacheConfiguration.defaultCacheConfig()
.serializeKeysWith(
RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(
RedisSerializationContext.SerializationPair.fromSerializer(genericJackson2JsonRedisSerializer))
.prefixKeysWith(keyPrefix);
} /*@Bean
public RedisCacheManager getRedisCacheManager(RedisConnectionFactory connectionFactory) { RedisCacheManagerBuilder redisCacheManagerBuilder = RedisCacheManagerBuilder.fromConnectionFactory(connectionFactory);
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
// Key
RedisSerializer<String> redisSerializerKey = new StringRedisSerializer();
SerializationPair<String> serializationPairKey = SerializationPair.fromSerializer(redisSerializerKey);
// Value
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(
Object.class);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
//
GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer(
objectMapper);
//RedisSerializer<Object> redisSerializerValue = jackson2JsonRedisSerializer;
//
RedisSerializer<Object> redisSerializerValue = genericJackson2JsonRedisSerializer;
//
SerializationPair<Object> serializationPairValue = SerializationPair.fromSerializer(redisSerializerValue);
//RedisSerializationContext.SerializationPair<Object> serializationPairValue = RedisSerializationContext.SerializationPair.fromSerializer(redisSerializerValue); //
redisCacheConfiguration.serializeKeysWith(serializationPairKey);
redisCacheConfiguration.serializeValuesWith(serializationPairValue);
redisCacheManagerBuilder.cacheDefaults(redisCacheConfiguration);
RedisCacheManager redisCacheManager = redisCacheManagerBuilder.build(); //
return redisCacheManager;
}*/ }
缓存测试的Controller
package com.smartmap.sample.test.controller.rest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import com.smartmap.sample.test.entity.User; @RestController
@RequestMapping("/api/v1.1/system/session")
public class SessionController {
final Log log = LogFactory.getLog(SessionController.class); @Autowired
RedisTemplate<String, Object> redisTemplate; /**
* curl -XPOST 'http://127.0.0.1:8080/test/api/v1.1/system/session/addSessionInfo'
* -H'Content-type:application/json;charset=UTF-8' -d ' { "id":123, "name":"123" }'
* @param request
* @param user
* @return
*/
@PostMapping("/addSessionInfo")
public User putSession(HttpServletRequest request, @RequestBody User user ){
HttpSession session = request.getSession();
log.info(session.getClass());
log.info(session.getId());
session.setAttribute("user", user);
redisTemplate.opsForValue().set("spring:manager:user", user);
return user;
} /**
* curl -XGET 'http://127.0.0.1:8080/test/api/v1.1/system/session/addSessionInfo/123/098'
* @param request
* @param user
* @return
*/
@GetMapping("/addSessionInfo/{userId}/{name}")
public User putSession(HttpServletRequest request, @PathVariable("userId") Long userId, @PathVariable("name") String name){
HttpSession session = request.getSession();
User user = new User();
user.setId(userId);
user.setName(name);
log.info(session.getClass());
log.info(session.getId());
session.setAttribute("user", user);
redisTemplate.opsForValue().set("spring:manager:user", user);
return user;
} /**
* curl -XGET 'http://127.0.0.1:8080/test/api/v1.1/system/session/getSessionInfo?userId=123'
* @param request
* @param userId
* @return
*/
@GetMapping("/getSessionInfo")
public User getSession(HttpServletRequest request, @RequestParam("userId") String userId){
log.info(request.getRemoteAddr());
HttpSession session = request.getSession();
User user = (User)session.getAttribute("user");
User userOther = (User)redisTemplate.opsForValue().get("spring:manager:user");
log.info(userOther.getName());
return user;
} }
启动两个应用
java -jar test.session-0.1.0.jar –-server.port=9000
java -jar test.session-0.1.0.jar –-server.port=9001
配置前端的Nginx来作为反向代理
upstream backend {
server 127.0.0.1:9000;
server 127.0.0.1:9001;
} server {
listen 80;
server_name localhost; #charset koi8-r; #access_log logs/host.access.log main;
location / {
proxy_pass http://backend;
index index.html index.htm;
} #location /Resource {
# #add_header 'Access-Control-Allow-Origin' '*';
# #add_header 'Access-Control-Allow-Credentials' 'true';
# #add_header 'Access-Control-Allow-Headers' '*';
# #add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,DELETE,PUT';
# root D:/Project;
# index index.html index.htm;
#} #error_page 404 /404.html; # redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
} # proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#} # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#} # deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#} }
访问服务(用浏览器)
http://127.0.0.1/test/api/v1.1/system/session/addSessionInfo/123/098
http://127.0.0.1/test/api/v1.1/system/session/getSessionInfo?userId=123
Spring Boot—19Session的更多相关文章
- 玩转spring boot——快速开始
开发环境: IED环境:Eclipse JDK版本:1.8 maven版本:3.3.9 一.创建一个spring boot的mcv web应用程序 打开Eclipse,新建Maven项目 选择quic ...
- 【微框架】之一:从零开始,轻松搞定SpringCloud微框架系列--开山篇(spring boot 小demo)
Spring顶级框架有众多,那么接下的篇幅,我将重点讲解SpringCloud微框架的实现 Spring 顶级项目,包含众多,我们重点学习一下,SpringCloud项目以及SpringBoot项目 ...
- 玩转spring boot——开篇
很久没写博客了,而这一转眼就是7年.这段时间并不是我没学习东西,而是园友们的技术提高的非常快,这反而让我不知道该写些什么.我做程序已经有十几年之久了,可以说是彻彻底底的“程序老炮”,至于技术怎么样?我 ...
- 玩转spring boot——结合redis
一.准备工作 下载redis的windows版zip包:https://github.com/MSOpenTech/redis/releases 运行redis-server.exe程序 出现黑色窗口 ...
- 玩转spring boot——AOP与表单验证
AOP在大多数的情况下的应用场景是:日志和验证.至于AOP的理论知识我就不做赘述.而AOP的通知类型有好几种,今天的例子我只选一个有代表意义的“环绕通知”来演示. 一.AOP入门 修改“pom.xml ...
- 玩转spring boot——结合JPA入门
参考官方例子:https://spring.io/guides/gs/accessing-data-jpa/ 接着上篇内容 一.小试牛刀 创建maven项目后,修改pom.xml文件 <proj ...
- 玩转spring boot——结合JPA事务
接着上篇 一.准备工作 修改pom.xml文件 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=&q ...
- 玩转spring boot——结合AngularJs和JDBC
参考官方例子:http://spring.io/guides/gs/relational-data-access/ 一.项目准备 在建立mysql数据库后新建表“t_order” ; -- ----- ...
- 玩转spring boot——结合jQuery和AngularJs
在上篇的基础上 准备工作: 修改pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=&q ...
随机推荐
- WPF一步步开发XMPP IM客户端2:主窗体设计
UI设计方案: 在设计窗体UI之前,先要了解一些主要的接口和帮助类: 对于主窗的左侧列表,容器内的Item必须实现ILeftItem的接口,比如联系人.系统消息.群等,接口包含点击事件 public ...
- [题解]luogu P4116 Qtree3
终于来到了Qtree3, 其实这是Qtree系列中最简单的一道题,并不需要线段树, 只要树链剖分的一点思想就吼了. 对于树链剖分剖出来的每一根重链,在重链上维护一个Set就好了, 每一个Set里存的都 ...
- css 题目笔记(本文收集了一些个人觉得比较有意思的css题目,欢迎大家给出自己的解答)
1.本文收集了一些个人觉得比较有意思的css题目,欢迎大家给出自己的解答 P标签的最大宽度不可以大于H2标签文字宽度的10% 这里应该是P标签的最大宽度由前面的匿名内联元素宽度(就是大字号文字宽度)决 ...
- 剑指offer三十五之数组中的逆序对
一.题目 在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对.输入一个数组,求出这个数组中的逆序对的总数P.并将P对1000000007取模的结果输出. 即输出P%1000 ...
- (转)linux如何让历史记录不记录敏感命令
有时候为了服务器安全,防止别人窥探我们输入的命令,我们可以清空历史记录,而更多的时候,我们选择的是在输入特殊命令时候,强制历史记录不记住该命令.实验方法:先执行export HISTCONTROL=i ...
- linux安装扩展总结
---恢复内容开始--- 1.安装php 模块安装命令. wget http://pear.php.net/go-pear 执行 php go_pear 如果是php7 wget http://pea ...
- Android Layout 01_activity_Login.xml
activity_login.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android ...
- docker网络之macvlan
macvlan接口类型简单说类似于子接口,但相比子接口来说,macvlan接口拥有自己独立的mac地址,因此使用macvlan接口可以允许更多的二层操作.macvlan有四种模式:VEPA,bridg ...
- Linux-(ps,grep)
grep命令 1.命令格式: grep [option] pattern file 2.命令功能: 用于过滤/搜索的特定字符.可使用正则表达式能多种命令配合使用,使用上十分灵活. Linux系统中gr ...
- C语言中判断字符串str1是否以str2开始或结束
#include <stdlib.h> #include <string.h> #include <stdio.h> /**判断str1是否以str2开头 * 如果 ...