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的更多相关文章

  1. 玩转spring boot——快速开始

    开发环境: IED环境:Eclipse JDK版本:1.8 maven版本:3.3.9 一.创建一个spring boot的mcv web应用程序 打开Eclipse,新建Maven项目 选择quic ...

  2. 【微框架】之一:从零开始,轻松搞定SpringCloud微框架系列--开山篇(spring boot 小demo)

    Spring顶级框架有众多,那么接下的篇幅,我将重点讲解SpringCloud微框架的实现 Spring 顶级项目,包含众多,我们重点学习一下,SpringCloud项目以及SpringBoot项目 ...

  3. 玩转spring boot——开篇

    很久没写博客了,而这一转眼就是7年.这段时间并不是我没学习东西,而是园友们的技术提高的非常快,这反而让我不知道该写些什么.我做程序已经有十几年之久了,可以说是彻彻底底的“程序老炮”,至于技术怎么样?我 ...

  4. 玩转spring boot——结合redis

    一.准备工作 下载redis的windows版zip包:https://github.com/MSOpenTech/redis/releases 运行redis-server.exe程序 出现黑色窗口 ...

  5. 玩转spring boot——AOP与表单验证

    AOP在大多数的情况下的应用场景是:日志和验证.至于AOP的理论知识我就不做赘述.而AOP的通知类型有好几种,今天的例子我只选一个有代表意义的“环绕通知”来演示. 一.AOP入门 修改“pom.xml ...

  6. 玩转spring boot——结合JPA入门

    参考官方例子:https://spring.io/guides/gs/accessing-data-jpa/ 接着上篇内容 一.小试牛刀 创建maven项目后,修改pom.xml文件 <proj ...

  7. 玩转spring boot——结合JPA事务

    接着上篇 一.准备工作 修改pom.xml文件 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=&q ...

  8. 玩转spring boot——结合AngularJs和JDBC

    参考官方例子:http://spring.io/guides/gs/relational-data-access/ 一.项目准备 在建立mysql数据库后新建表“t_order” ; -- ----- ...

  9. 玩转spring boot——结合jQuery和AngularJs

    在上篇的基础上 准备工作: 修改pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=&q ...

随机推荐

  1. python操作oracle数据库-查询

    python操作oracle数据库-查询 参照文档 http://www.oracle.com/technetwork/cn/articles/dsl/mastering-oracle-python- ...

  2. easyUI制作slider小滑块,可拖动和精确输入

    借助easyUI制作.完善slider小滑块. 可拖动.和在右边输入框精确输入 效果图: html代码: <div class="text_fl" >亮度设置:< ...

  3. Linux终端复用工具 tmux

    简介 Terminal Multiplexer (From WIKIPEDIA) - A terminal multiplexer is a software application that can ...

  4. Linux Cluster环境下批量分发执行补丁

    转自:http://blog.csdn.net/napolunyishi/article/details/18219867 这两天做了一个需求,因为上一个版本的/tmp空间默认只分配了5G,而升级程序 ...

  5. centos 6.8 解决ibus输入法不正常显示的问题

    今天发现 ibus输入法打字时不正常显示,如下图

  6. (转)Mysql技术内幕InnoDB存储引擎-表&索引算法和锁

    表 原文:http://yingminxing.com/mysql%E6%8A%80%E6%9C%AF%E5%86%85%E5%B9%95innodb%E5%AD%98%E5%82%A8%E5%BC% ...

  7. Java之集合(四)Vector和Stack

    转载请注明源出处:http://www.cnblogs.com/lighten/p/7296023.html 1.前言 本章介绍Java集合List中的Vector和其子类Stack.Vector类是 ...

  8. 使用Intent在活动之间穿梭

    使用Intent在活动之间穿梭 1.在com.example.activitytest中创建第二个活动SecondActivity: /** * 第二个活动 */ public class Secon ...

  9. Android版本分布——2017年5月更新

    Code Name Version API Level Last month This month Change gingerbread(姜饼) 2.3.3——2.3.7 10 0.9% 1.0% 0 ...

  10. as和is,但is也有as所没有的功能[C#] --转载 甘木

    在C#中,我们可以使用is as操作符来判断某数据类型和其它指定类型的关系 1. 用is运算符验证基础类型 C#允许在继承链中向下转型,所以如果DerivedClass派生自BaseClass,那么D ...