springboot2.x使用redis作为缓存,自定义序列化和反序列化

SpringBoot2.x和1.x的区别很大,比如在整合 Redis 这一块,RedisCacheManager就有不同。

application.properties

# database name
spring.redis.database=0
# server host1
# spring.redis.host=127.0.0.1
spring.redis.host=47.112.4.110
# server password
# spring.redis.password=123456
spring.redis.password=
#connection port
spring.redis.port=6379
# pool settings ...
spring.redis.jedis.pool.max-idle=8 
spring.redis.jedis.pool.min-idle=0
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-wait=-1

redis配置类:(最重要的的是配置类)

@Configuration
@EnableCaching
public class redisConf {
    //过期时间30秒
    private Duration timeToLive = Duration.ofSeconds(30L);
    Logger log= LoggerFactory.getLogger(getClass());
    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        //默认1
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(this.timeToLive)
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer()))
                .disableCachingNullValues();
        RedisCacheManager redisCacheManager = RedisCacheManager.builder(connectionFactory)
                .cacheDefaults(config)
                .transactionAware()
                .build();
        log.debug("自定义RedisCacheManager加载完成");
        return redisCacheManager;
    }
    @Bean(name = "redisTemplate")
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(keySerializer());
        redisTemplate.setHashKeySerializer(keySerializer());
        redisTemplate.setValueSerializer(valueSerializer());
        redisTemplate.setHashValueSerializer(valueSerializer());
        log.debug("自定义RedisTemplate加载完成");
        return redisTemplate;
    }
    private RedisSerializer keySerializer() {
        return new StringRedisSerializer();
    }
    private RedisSerializer valueSerializer() {
        return new GenericJackson2JsonRedisSerializer();
    }
}
 
  

domain

public class Department implements Serializable {

    private Integer id;
    private String departmentName;

    public void setId(Integer id) {
        this.id = id;
    }

    public void setDepartmentName(String departmentName) {
        this.departmentName = departmentName;
    }

    public Integer getId() {
        return id;
    }

    public String getDepartmentName() {
        return departmentName;
    }

    @Override
    public String toString() {
        return "Department{" +
                "id=" + id +
                ", departmentName='" + departmentName + '\'' +
                '}';
    }
}

mapper


@Mapper
public interface departmentMapper {

    @Select("select * from department where id=#{id}")
    public Department getDeptById(Integer id);

    @Delete("delete from department where id=#{id}")
    public int deleteDeptById(Integer id);

    @Options(useGeneratedKeys = true,keyProperty = "id")
    @Insert("insert into department(departmentName) values(#{departmentName})")
    public int insertDept(Department department);

    @Update("update department set departmentName=#{departmentName} where id=#{id}")
    public int updateDept(Department department);

}

service

@Service
public class departmentService implements IdepartmentService{

    @Autowired
    departmentMapper departmentMapper;

    @Cacheable(cacheNames = "dept", unless = "#result == null ")
    public Department getDeptById(Integer id){
        System.out.println("查询部门"+id);
        Department department = departmentMapper.getDeptById(id);
        return department;
    }
}

controller

@RestController
public class departmentController {

    @Autowired
    departmentService departmentService;

    @GetMapping("/dept/{id}")
    public Department getDepartment(@PathVariable(value = "id") Integer id){

        //return departmentService.getBYid(id);
        return  departmentService.getDeptById(id);
    }
}

测试类

@SpringBootTest
class DemodruidApplicationTests {

    @Autowired
    StringRedisTemplate stringRedisTemplate;  //操作k-v都是字符串的
    @Autowired
    RedisTemplate redisTemplate;  //k-v都是对象的
    @Autowired
    EmployeeService employeeService;
    @Autowired
    departmentService departmentService;

    /**
     * Redis常见的五大数据类型
     *  String(字符串)、List(列表)、Set(集合)、Hash(散列)、ZSet(有序集合)
     *  stringRedisTemplate.opsForValue()[String(字符串)]
     *  stringRedisTemplate.opsForList()[List(列表)]
     *  stringRedisTemplate.opsForSet()[Set(集合)]
     *  stringRedisTemplate.opsForHash()[Hash(散列)]
     *  stringRedisTemplate.opsForZSet()[ZSet(有序集合)]
     */
    @Test
    public void test01(){
//        给redis中保存数据
        stringRedisTemplate.opsForValue().append("msg","hello");
		String msg = stringRedisTemplate.opsForValue().get("msg");
		System.out.println(msg);

		stringRedisTemplate.opsForList().leftPush("mylist","1");
        stringRedisTemplate.opsForList().leftPush("mylist","2");
        stringRedisTemplate.opsForList().leftPush("mylist","zyr");
        stringRedisTemplate.opsForList().leftPush("mylist","渔人");
        System.out.println(stringRedisTemplate.opsForList().leftPop("mylist"));
        System.out.println(stringRedisTemplate.opsForList().rightPop("mylist"));
        try {
            String ip = InetAddress.getLocalHost().getHostAddress();
            stringRedisTemplate.opsForValue().set(ip,"0",30,TimeUnit.SECONDS);
            //stringRedisTemplate.expire(ip,30, TimeUnit.SECONDS);
            System.out.println(ip+":"+stringRedisTemplate.opsForValue().get(ip));
            stringRedisTemplate.opsForValue().increment(ip);
            stringRedisTemplate.opsForValue().increment(ip);
            stringRedisTemplate.opsForValue().increment(ip);
            System.out.println(ip+":"+stringRedisTemplate.opsForValue().get(ip));
            if(Integer.parseInt(stringRedisTemplate.opsForValue().get(ip))>2){
                System.out.println("拒绝访问");
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test04(){
        String ip="0:0:0:0:0:0:0:1";
        if(stringRedisTemplate.hasKey("IP:"+ip)){
            stringRedisTemplate.opsForValue().increment("IP:"+ip);
            if(Integer.parseInt(stringRedisTemplate.opsForValue().get("IP:"+ip))>=3){
                System.out.println("IP访问次数超过,防止洪水攻击!!!");
            }
        }else {
            stringRedisTemplate.opsForValue().set("IP:"+ip,"0");
        }

    }

    //测试保存对象
    @Test
    public void test02(){
        Employee empById = employeeService.getEmpById(1);
        Department department=departmentService.getBYid(2);
        //默认如果保存对象,使用jdk序列化机制,序列化后的数据保存到redis中
        //edisTemplate.opsForValue().set("emp-01",empById);
        //1、将数据以json的方式保存
        //(1)自己将对象转为json
        //(2)redisTemplate默认的序列化规则;改变默认的序列化规则;
        //empRedisTemplate.opsForValue().set("emp-01",empById);
        //deptRedisTemplate.opsForValue().set("dept-2",department);
        redisTemplate.opsForValue().set("emp-01",empById);
        redisTemplate.opsForValue().set("dept-2",department);

    }
    @Test
    public void testJson(){
        Employee empById = employeeService.getEmpById(1);
        stringRedisTemplate.opsForValue().set("json-emp-01-new",JsonUtils.objectToJson(empById));
        System.out.println(JsonUtils.jsonToPojo(stringRedisTemplate.opsForValue().get("json-emp-01-new"),Employee.class).toString());
        logger.info(JsonUtils.jsonToPojo(stringRedisTemplate.opsForValue().get("json-emp-01-new"),Employee.class).toString());
    }
}
public class JsonUtils {
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 将对象转换成json字符串。
     * 

Title: pojoToJson

*

Description:

* @param data * @return */
public static String objectToJson(Object data) { try { String string = MAPPER.writeValueAsString(data); return string; } catch (JsonProcessingException e) { e.printStackTrace(); } return null; } /** * 将json结果集转化为对象 * * @param jsonData json数据 * @param beanType 对象中的object类型 * @return */ public static <T> T jsonToPojo(String jsonData, Class<T> beanType) { try { T t = MAPPER.readValue(jsonData, beanType); return t; } catch (Exception e) { e.printStackTrace(); } return null; } /** * 将json数据转换成pojo对象list *

Title: jsonToList

*

Description:

* @param jsonData * @param beanType * @return */
public static <T> List<T> jsonToList(String jsonData, Class<T> beanType) { JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType); try { List<T> list = MAPPER.readValue(jsonData, javaType); return list; } catch (Exception e) { e.printStackTrace(); } return null; } }

你可能感兴趣的:(springboot2.x使用redis作为缓存,自定义序列化和反序列化)