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 ...
随机推荐
- XP系统安装VS2010失败的解决方法
今天装了一个双系统,但是在XP系统上安装VS2010的时候就出现了下面的错误 于是在网上搜索各种资源,查看错误日志,网上说是office2007的原因,我也抱着试试看的态度去卸载了,可是卸载后却发现还 ...
- Mac下使用zsh不执行/etc/profile文件
Mac下使用了zsh会不执行/etc/profile文件,当然,如果用原始的是会执行. 转而执行的是这两个文件,每次登陆都会执行: ~/.zshrc与/etc/zshenv与/etc/zshrc 所以 ...
- ubuntu编译安装ruby1.9.3,从p551降级到p484
在升级redmine的时候遇到ruby版本适配的问题.找了些资料. ruby安装包除了官方网站,可以参考 http://ftp.ruby-lang.org/pub/ruby/1.9/ 需要从1.9.3 ...
- warning: already initialized constant FileUtils::VERSION
Ran into this, and the solution here works: https://stackoverflow.com/questions/51334732/rails-5-2-0 ...
- linux安装tmux
由于tmux依赖于libevent和ncurses-devel,所以应首先有这两个库,和相关的头文件. 1.对于ncurses-devel,可用yum安装. yum install ncurses-d ...
- 自然语言处理--N-gram
考虑一个语音识别系统,假设用户说了这么一句话:“I have a gun”,因为发音的相似,该语音识别系统发现如下几句话都是可能的候选:1.I have a gun. 2.I have a gull. ...
- tomcat安装以及常用配置
目录 一 什么是tomcat 二 tomcat 的版本: 三 tomcat的下载 3.1 tomcat9版本下载链接 3.2 tomcat8.5版本下载链接 四 tomcat的安装 4.1 java环 ...
- jetty9优化的两处地方
http://www.cnblogs.com/LBSer/p/3637387.html jetty 9两个优化: https://webtide.intalio.com/2013/01/jetty-9 ...
- mysql空间扩展 VS PostGIS
http://www.cnblogs.com/LBSer/p/3629149.html 功能 Mysql spatial extension PostGIS 空间索引 仅MyISAM支持R树索引,I ...
- Servlet多文件上传方法
1. 通过getInputStream()取得上传文件. 001 /** 002 * To change this template, choose Tools | Templates 003 * ...