springboot使用redis(第一篇)

一隻小小小柒發表於2018-08-29

1.在pom.xml檔案中配置需要的jar包

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-redis</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-cache</artifactId></dependency>

2.在配置檔案中配置redis連線資訊

cas.ticket.registry.redis.database=0
cas.ticket.registry.redis.port=6379
cas.ticket.registry.redis.host=127.0.0.1

 

3.redis鍵生成配置(將RedisTemplate配置成Bean

package com.winstar.redis;
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.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
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 java.lang.reflect.Method;
 
 
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{
 
    private final static String redis_key_questions="ACTIVITY_QUESTION";
    private final static String redis_key_annual="ACTIVITY_ANNUAL";
    private final static String redis_key_action="ACTIVITY_ACTION";
 
 
    @Bean
    public KeyGenerator ACTIVITY_QUESTION_KEY(){
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
 
                return redis_key_questions;
            }
        };
 
    }
 
    @Bean
    public KeyGenerator ACTIVITY_ACTION_KEY(){
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
 
                return redis_key_action;
            }
        };
 
    }
 
    @Bean
    public KeyGenerator ACTIVITY_ANNUAL_KEY(){
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
 
                return redis_key_annual;
            }
        };
 
    }
 
    @Bean
    public KeyGenerator KeyGenerator(){
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
 
    }
 
    @Bean
    public CacheManager cacheManager(
            @SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
        return new RedisCacheManager(redisTemplate);
    }
 
    @Bean
    public RedisTemplate<String, String> redisTemplate(
            RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}

 

4.實體類(需要實現Serializable)

import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import java.io.Serializable;
import java.util.Date;


public class UserInfo  implements Serializable {

    private static final long serialVersionUID = -1L;

    private String usercode;

    private String password;


    @Temporal(TemporalType.TIMESTAMP)
    private Date passwordsetdate; // 日期型別,格式:yyyy-MM-dd HH:mm:ss
 

    public String getUsercode() {
        return usercode;
    }

    public void setUsercode(String usercode) {
        this.usercode = usercode;
    }

    public String getPassword() {
        return password;
    }

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

    public String getUsercname() {
        return usercname;
    }

    public void setUsercname(String usercname) {
        this.usercname = usercname;
    }

    public Date getCreatetime() {
        return createtime;
    }

    public void setCreatetime(Date createtime) {
        this.createtime = createtime;
    }

 
}

 

5.專案啟動時讀取指定表的資料快取到redis

@Controller
@RequestMapping("/user")
public class UserController implements InitializingBean {
    @Autowired
    JdbcTemplate jdbcTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        List<UserInfo> userInfoList = jdbcTemplate.query(USER_SQL, new BeanPropertyRowMapper<UserInfo>(UserInfo.class));
        if (userInfoList == null) {
            return;
        }
        for(UserInfo u :userInfoList){


       redisTemplate.opsForValue().set(u.getUsercode(), u);
        }
      }
}

這樣子就將指定的user表的資料快取到了redis當中。

這是第一次寫文章,也是剛開始接觸springboot,可以加qq741751051相互學習。

相關文章