Springbootはredisを統合し、共有セッションを実現する


最近springbootでredisを統合してキャッシュをしているとき、たくさんの穴を踏んでいますね.ああ、前後2晩振り回しました.今度また穴を踏まないように、ここに記録してください.pom.xml:

		
			redis.clients
			jedis
		
		
		
			org.apache.commons
			commons-pool2
			2.5.0
		

propertiesファイル構成;
# REDIS (RedisProperties)
# Redis     (   0)
spring.redis.database=0
# Redis     
spring.redis.host=127.0.0.1
# Redis       
spring.redis.port=6379
# Redis       (    )
spring.redis.password=
#       (  )
spring.redis.timeout=10000
#         (          )
spring.redis.jedis.pool.max-active=8
#            (          )
spring.redis.jedis.pool.max-wait=-1
#            
spring.redis.jedis.pool.max-idle=8
#            
spring.redis.jedis.pool.min-idle=0

configクラス:
package com.xiangzhang.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
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.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

/**
 * redis   
 *
 * @author jie ON 2019/3/14
 **/
@Configuration
@EnableCaching
public class RedisConfig {
    @Bean
    /**
     *            cacheManager
     */
    CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        //     RedisCacheWriter
        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory);
        RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig();
        //          1 
        defaultCacheConfig.entryTtl(Duration.ofDays(1));
        //   RedisCacheManager
        RedisCacheManager cacheManager = new RedisCacheManager(redisCacheWriter, defaultCacheConfig);
        return cacheManager;
    }

    /**
     *     redisTemplate        
     */
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        //  Jackson2JsonRedisSerializer         redis value (    JDK      )
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(mapper);

        template.setValueSerializer(serializer);
        //  StringRedisSerializer         redis key 
        template.setKeySerializer(new StringRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }

    @Bean
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(factory);
        return stringRedisTemplate;
    }
}

beanクラス:
package com.xiangzhang.entity;

import com.gitee.sunchenbin.mybatis.actable.annotation.Column;
import com.gitee.sunchenbin.mybatis.actable.annotation.Table;
import com.gitee.sunchenbin.mybatis.actable.command.BaseModel;
import com.gitee.sunchenbin.mybatis.actable.constants.MySqlTypeConstant;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author    
 * @date 2019-3-2
 */

@Data
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "hero")
public class User extends BaseModel {
    /**
     *                      
     */
    @Column(name = "id",type = MySqlTypeConstant.INT,length = 11,isKey = true,isAutoIncrement = true)

    private int id;

    @Column(name = "name",type = MySqlTypeConstant.VARCHAR,length = 111)

    private String name;

    @Column(name = "hp",type = MySqlTypeConstant.DOUBLE,length = 16,decimalLength = 2)

    private double hp;

    @Column(name = "damage",type = MySqlTypeConstant.DOUBLE,length = 16,decimalLength = 2)

    private double damage;
}


テストクラス:
package com.xiangzhang;

import com.xiangzhang.entity.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;


@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
	private static final Logger log = LoggerFactory.getLogger(DemoApplicationTests.class);
	@Autowired
	RedisTemplate redisTemplate;

	@Test
	public void get(){

		String key = "balabala";
		redisTemplate.opsForValue().set(key,"lalala");
		final String k2 = (String)redisTemplate.opsForValue().get(key);
		log.info("[          ] - [{}]",k2);

		redisTemplate.opsForValue().set(key,new User(11,"  ",123,485));
		final User user = (User)redisTemplate.opsForValue().get(key);
		log.info("[          ] - [{}]",user);
	}
}

ここでいくつか注意しなければならない問題は、実行前にローカルまたはあなたのサーバでredisのサービス側を開かなければなりません.そうしないと、接続が間違っていて接続できません.私はパスワード構成の問題だと思っていました.
共有セッションの構成:pom.xml:

		
			org.springframework.session
			spring-session-data-redis
		
		
			nl.bitwalker
			UserAgentUtils
			1.2.4
		
		
			commons-codec
			commons-codec
			1.6
		

configクラス:
package com.xiangzhang.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;

/**
 * @author    
 * @date 2019/3/14
 */

@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 86400*30)
public class SessionConfig {
}


コントロールクラスのテスト:
package com.xiangzhang.controller;

import com.xiangzhang.entity.User;
import com.xiangzhang.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author    
 * @date 2019/3/14
 */

@Controller
@RequestMapping
public class UserRedisController {

    @Autowired
    UserMapper userMapper;

    @GetMapping(value = "/user")
    public List getAllUser() {
        return this.userMapper.returnResult();
    }

    @GetMapping(value = "/user/{id}")
    @Cacheable(value = "user-key")
    public User getUserById(@PathVariable("id") int id) {
        return userMapper.returnById(id);
    }

    @RequestMapping(value = "/test/cookie")
    public String getCookie(@RequestParam("token") String token, HttpServletRequest request, HttpSession session){
        Object sesssionToken = session.getAttribute("token");
        if(sesssionToken == null){
            System.out.println("   session,  session = " + token);
            session.setAttribute("token",token);
        }else {
            System.out.println("  session = " + sesssionToken.toString());
        }
        Cookie[] cookies = request.getCookies();
        if(cookies != null && cookies.length > 0){
            for(Cookie cookie : cookies){
                System.out.println(cookie.getName() + ":" + cookie.getValue());
            }
        }
        return "footer";
    }
}