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