Redis is used in SpringBoot

Redis application scenarios:

  • Caching (data queries, short links, news content, product content, and so on). (Maximum use)
  • Distributed cluster architecturesessionSeparation.
  • A chat room’s list of online friends.
  • Task queues. (Seckill, Snap, 12306, etc.)
  • App leaderboards.
  • Website visit statistics.
  • Data expiration processing (to the millisecond)

With SpringBoot, you can quickly add redis relational databases to your project.

redis.properties

# how redis connection configuration spring. Redis. Shard. The hostname =192.16810.110.
spring.redis.shard.password =
spring.redis.shard.port = 6379

spring.redis.pool.maxIdle = 20
spring.redis.pool.maxTotal = 500
spring.redis.pool.numTestsPerEvictionRun = 3
spring.redis.pool.testOnBorrow = true
spring.redis.pool.blockWhenExhausted = false
spring.redis.pool.testOnReturn = false
Copy the code

Redis configuration class

@Component
@PropertySource("redis.properties")
public class JedisConfig implements Serializable {

    private static final long serialVersionUID = 1L;

    @Value("${spring.redis.shard.hostname}")
    private String hostname;
    @Value("#{${spring.redis.shard.port}}")
    private int port;
    @Value("${spring.redis.shard.password}")
    private String password;
    @Value("#{${spring.redis.pool.maxIdle}}")
    private Integer maxTotal;
    @Value("#{${spring.redis.pool.maxTotal}}")
    private Integer maxIdle;

    private boolean testOnBorrow;
    private boolean testOnReturn;

    public String getHostname(a) {
        return hostname;
    }

    public void setHostname(String hostname) {
        this.hostname = hostname;
    }

    public int getPort(a) {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getPassword(a) {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getMaxTotal(a) {
        return maxTotal;
    }

    public void setMaxTotal(Integer maxTotal) {
        this.maxTotal = maxTotal;
    }

    public Integer getMaxIdle(a) {
        return maxIdle;
    }

    public void setMaxIdle(Integer maxIdle) {
        this.maxIdle = maxIdle;
    }




    public boolean isTestOnBorrow(a) {
        return testOnBorrow;
    }

    public void setTestOnBorrow(boolean testOnBorrow) {
        this.testOnBorrow = testOnBorrow;
    }

    public boolean isTestOnReturn(a) {
        return testOnReturn;
    }

    public void setTestOnReturn(boolean testOnReturn) {
        this.testOnReturn = testOnReturn;
    }

    @Override
    public String toString(a) {
        return "JedisConfig{" +
                "hostname='" + hostname + '\' ' +
                ", port=" + port +
                ", password='" + password + '\' ' +
                ", maxTotal=" + maxTotal +
                ", maxIdle=" + maxIdle +
                ", testOnBorrow=" + testOnBorrow +
                ", testOnReturn=" + testOnReturn +
                '} ';
    }
Copy the code

Use the redisTemplate to operate via redis

@Configuration
public class JedisConfiguration {
    @Autowired
    JedisConfig redisConfig;
    public JedisConnectionFactory convertJedisConnectionFactory(a) {

        System.out.println(redisConfig);
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
        jedisConnectionFactory.setHostName(redisConfig.getHostname());
        jedisConnectionFactory.setPort(redisConfig.getPort());
        jedisConnectionFactory.setPassword(redisConfig.getPassword());

        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(redisConfig.getMaxTotal());
        jedisPoolConfig.setMaxIdle(redisConfig.getMaxIdle());
        jedisPoolConfig.setMinIdle(20);
       jedisPoolConfig.setMaxWaitMillis(300000000);
        jedisPoolConfig.setTestOnBorrow(redisConfig.isTestOnBorrow());
        jedisPoolConfig.setTestOnReturn(redisConfig.isTestOnReturn());
       // jedisPoolConfig.setTestWhileIdle();

        jedisConnectionFactory.setPoolConfig(jedisPoolConfig);
        jedisConnectionFactory.afterPropertiesSet();
        return jedisConnectionFactory;
    }

    @Bean(name = "redisTemplate")
    public StringRedisTemplate convertStringRedisTemplate(a) {
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(convertJedisConnectionFactory());
        stringRedisTemplate.setDefaultSerializer(new GenericJackson2JsonRedisSerializer());   // Here you can set the serialization mode, which can be saved in Redis as json
        return stringRedisTemplate;
    }



    @Bean(value = "template")
    public RedisTemplate<String,Object>redisTemplate()
    {
        RedisTemplate<String,Object> template =new RedisTemplate<>();
        template.setConnectionFactory(convertJedisConnectionFactory());

        Jackson2JsonRedisSerializer jsonRedisSerializer=new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om=new ObjectMapper();
        // Specify the serialized domain
        om.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY);
        // Specify the type of serialized input (excluding final types)
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jsonRedisSerializer.setObjectMapper(om);

        // The body selects the serialization mode JSON
        template.setDefaultSerializer(jsonRedisSerializer);


        / / the Map section
        // Serialize and deserialize the key of redis
        template.setKeySerializer(new StringRedisSerializer());
        // Set the hash key and value serialization mode
        template.setHashKeySerializer( new StringRedisSerializer());
        template.setHashValueSerializer(jsonRedisSerializer);

        // Indicates that the configuration is complete
        template.afterPropertiesSet();
        return template;
    }


    // One-to-one data type
    @Bean(name ="ObjectredisTemplate")
    public ValueOperations<String,Object>valueOperations(RedisTemplate<String,Object> template)
    {
        returntemplate.opsForValue(); }}Copy the code

The test class

@Controller
public class maincontroller {

    @Resource(name = "ObjectredisTemplate")
    ValueOperations<String,Object> valueOperations;


    @Resource(name = "redisTemplate")
    StringRedisTemplate stringRedisTemplate;


    @Autowired
    JedisConfig redisConfig;
    @RequestMapping("/")
    public void test(a) throws Exception
    {

        /* system.out. println(" already accessed "); System.out.println(redisConfig); String a= stringRedisTemplate.opsForValue().get("a"); * /

// JSONObject jsonObject =new JSONObject();
// jsonObject.put("name"," name");
// jsonObject.put(" age ",18);
//
// valueOperations.set("user",jsonObject);



        //JSONObject jsonObject1=(JSONObject) valueOperations.get("user");


        System.out.println();


        Thread thread =new Thread(new Runnable() {
            @Override
            public void run(a) {

                String a=stringRedisTemplate.opsForValue().get("a");
                System.out.println(a);

                User user =new User();
                user.setName("hahah");
                user.setAge(5); valueOperations.set(user.getName(),user); User user1 =(User) valueOperations.get(user.getName()); System.out.println(user1); }}); thread.start(); thread.join(); }Copy the code

The execution result