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 ...
 
随机推荐
- day 55 linux 的常用命令
			
前言 前面咱们已经成功安装了Linux系统--centos7,那么我们现在提好裤腰带,准备奔向Linux的大门. Linux命令行的组成结构 [root@oldboy_python ~]# [roo ...
 - 转的很好的js 入门
			
JavaScript概述 JavaScript的历史 1992年Nombas开发出C-minus-minus(C--)的嵌入式脚本语言(最初绑定在CEnvi软件中).后将其改名ScriptEase.( ...
 - 使用SUI框架下的<a>标签点击跳转页面不刷新的问题
			
最近写好了几个页面,今天试着将各个页面的链接打通,然后问题就来了...(╯︵╰) 这里看一下原来想要实现的两个页面跳转的效果--点击图一标注的栏目可以跳转到一个新的页面图二... 按照之前写a标签的跳 ...
 - uiautomatorviewer 双击闪退问题解决
			
最近在学习app自动测试,结果在打开uiautomatorviewer查看app界面元素时,就出现了闪退的问题,找了很多很多方法,最后终于可以解决了,详情请继续往下看 首次安装adt的步骤 将下载的压 ...
 - 认识AngularJS
			
学习AngularJS所需技能 HTML & CSS JavaScript 为什么要使用AngularJS 如果你想用JavaScript制作动态Web站点,使用AngularJS有以下优点: ...
 - C#获取获取北京时间多种方法
			
#region 获取网络时间 ///<summary> /// 获取中国国家授时中心网络服务器时间发布的当前时间 ///</summary> ///<returns> ...
 - Tomcat发生java.lang.OutOfMemoryError: PermGen space的解决方案
			
产生该问题的主要原因是JVM永久带空间不足导致的,可以在环境变量CATALINA_OPTS中提高MaxPermSize参数值 set CATALINA_OPTS = -XX:PermSize=12 ...
 - python的字符串内建函数(方法)
			
原本总结一下,后来发现这个里面讲的很全,可以点进去参考:http://www.runoob.com/python/python-strings.html
 - 【链表】Remove Duplicates from Sorted List II(三指针)
			
题目: Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct ...
 - tomcat 日志详解
			
1 tomcat 日志详解 1.1 tomcat 日志配置文件 tomcat 对应日志的配置文件:tomcat目录下的/conf/logging.properties. tomcat 的日志等级有 ...