SpringBoot2.0整合redis完整源码

源码github地址:

https://github.com/tonnyzt/springboot.git

 

  • 1、引入redis框架,当然版本需要和springboot的版本一致
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <version>2.0.4.RELEASE</version>
</dependency>
  • 2、配置application.yml

 

 目前是配置的单机

spring:
  redis:
    database: 0
    password: 123456
    host: localhost
    port: 6379
    jedis:
      pool:
        max-idle: 100
        min-idle: 1
        max-active: 300
        max-wait: -1
  • 3、配置redis缓存管理器,和redis模板
package com.org.springboot.serve.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.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.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * Redis config files
 *
 * @Author: Tonny
 * @CreateDate: 18/11/19 下午 03:33
 * @Version: 1.0
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
    /**
     * 生成key的策略
     *
     * @return
     */
    @Bean
    public KeyGenerator keyGenerator() {
        return (target, method, 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();
        };
    }

    /**
     * 缓存管理器
     *
     * @param connectionFactory
     * @return CacheManager
     */
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        //初始化一个RedisCacheWriter
        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory);
        RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig();

        // springboot2.0需要在缓存管理的时候对key和value进行序列化操作
        // springboot1.0可以不用下面3行
        RedisSerializer redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer serializer = this.getSerializer();
        RedisCacheConfiguration redisCacheConfiguration = defaultCacheConfig
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(serializer));

        //设置默认超过期时间是1000秒
//        defaultCacheConfig.entryTtl(Duration.ofSeconds(1000));
        //初始化RedisCacheManager
        RedisCacheManager cacheManager = new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);
        return cacheManager;
    }

    /**
     * 序列化key和value,防止乱码
     * @return
     */
    private Jackson2JsonRedisSerializer getSerializer() {
        // 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper mapper = new ObjectMapper();
        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(mapper);
        return serializer;
    }

    /**
     * RedisTemplate配置
     *
     * @param factory redis工厂
     * @return RedisTemplate
     */
    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {

        StringRedisTemplate template = new StringRedisTemplate(factory);
        RedisSerializer stringSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer serializer = this.getSerializer();

        // 值采用json序列化
        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(stringSerializer);
        template.setValueSerializer(serializer);

        // 设置hash key 和value序列化模式
        template.setHashKeySerializer(stringSerializer);
        template.setHashValueSerializer(serializer);

        template.afterPropertiesSet();
        return template;
    }
}

上述redis的基础配置就配置完了

下面我们来实际查询试试

  • 4、实体类,DAO,Service,Test

   一定需要继承Serializable 

@Data
public class User implements Serializable {
    private String id;
    private String name;
    private String age;
}

dao文件 

public interface UserDao {
    User getById(Long id);

    List<User> getAll();

    int updateUser(User user);

    int deleteById(Long id);

    int insert(User user);
}

mapper文件 

<select id="getAll" resultMap="getMap">
        select * from user
    </select>

    <select id="getById" resultType="com.org.springboot.entity.User"
            parameterType="long">

        select * from user where id = #{0}
    </select>

    <update id="updateUser" parameterType="com.org.springboot.entity.User">
        update user set name = #{name},age = #{age} where id = #{id}
    </update>

    <delete id="deleteById" parameterType="long">
        delete from user where id = #{0}
    </delete>

    <insert id="insert" parameterType="com.org.springboot.entity.User"
            useGeneratedKeys="true" keyProperty="id" keyColumn="id">

        INSERT INTO user (name, age) VALUES (#{name}, #{age});
    </insert>

 service实现了,当然还有借口类,我就不贴出来了

package com.org.springboot.service.impl;


import com.org.springboot.dao.UserDao;
import com.org.springboot.entity.User;
import com.org.springboot.serve.redis.RedisService;
import com.org.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public List<User> getAll() {
        return userDao.getAll();
    }

    @Override
    @Cacheable(value = "User", key = "'user'.concat(#id.toString())")
    public User getById(Long id) {
        return userDao.getById(id);
    }

    @Override
    @CachePut(value = "User", key = "'user'.concat(#user.id.toString())")
    public User updateUser(User user) {
        userDao.updateUser(user);
        return user;
    }

    @Override
    @CacheEvict(value = "User", key = "'user'.concat(#id.toString())")
    public int deleteById(Long id) {
        return userDao.deleteById(id);
    }

    @Override
    @CachePut(value = "User", key = "'user'.concat(#user.id.toString())")
    public User add(User user) {
        userDao.insert(user);
        return user;
    }

    /**
     * keyGenerator策略生产key
     *
     * @param param1
     * @param param2
     * @return
     */
    @Cacheable(value = "redis", key = "#p0")
    @Override
    public String cacheKeyGenerator(String param1, String param2) {
        String str = param2;
        return str;
    }
}
  • 5、单元测试类
package com.org.springboot.test;

import com.alibaba.fastjson.JSONObject;
import com.org.springboot.SpringbootApplication;
import com.org.springboot.entity.User;
import com.org.springboot.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;


@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = SpringbootApplication.class)
public class UserTest {
    @Autowired
    private UserService service;

    @Test
    public void getAll() {
        List<User> list = service.getAll();
        System.out.println(JSONObject.toJSONString(list));
    }

    @Test
    public void add() {
        User user = new User();
        user.setName("王四");
        user.setAge(3);
        user = service.add(user);
        System.out.println(JSONObject.toJSONString(user));
    }

    @Test
    public void getById() {
        User user = service.getById(1L);
        System.out.println(JSONObject.toJSONString(user));
    }

    @Test
    public void updateUser() {
        int result = service.deleteById(1L);
        System.out.println(result);
    }
}

6、测试

先看redis里面的key为空

127.0.0.1:6379> keys *

127.0.0.1:6379>

执行add()添加方法:

程序控制台返回结果:{"age":3,"id":1,"name":"王四"}
==========================================

redis控制台:
==========================================
127.0.0.1:6379> keys *

127.0.0.1:6379> keys *
User::user1
127.0.0.1:6379> get User::user1
{"id":1,"name":"王四","age":3}
127.0.0.1:6379>


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值