springboot-整合redis

springboot 集成redis有两种方式

  • 1、手动配置集成jedis
  • 2、使用spring-boot-starter-data-redis集成

手动配置集成jedis

1、添加依赖

jedis:连接redis
fastjson: 序列化工具,序列化为json格式

<dependency>
	    <groupId>redis.clients</groupId>
	    <artifactId>jedis</artifactId>
	</dependency>
	
	<dependency>
	    <groupId>com.alibaba</groupId>
	    <artifactId>fastjson</artifactId>
	    <version>1.2.38</version>
	</dependency>
	
2、配置属性
# redis
redis.host=localhost
redis.port=6379
redis.timeout=3
redis.password=
redis.poolMaxTotal=10
redis.poolMaxIdle=10
redis.poolMaxWait=3
3、配置redis组件
@Component
@ConfigurationProperties(prefix="redis")
public class RedisConfig {
    private String host;
    private int port;
    private int timeout;//秒
    private String password;
    private int poolMaxTotal;
    private int poolMaxIdle;
    private int poolMaxWait;//秒
    //setter and getter
}
4、创建redispool
@Service
public class RedisPoolFactory {

    @Autowired
    RedisConfig redisConfig;

    //redis无密码时,redisConfig.getPassword()改为null
    @Bean
    public JedisPool JedisPoolFactory() {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(redisConfig.getPoolMaxIdle());
        poolConfig.setMaxTotal(redisConfig.getPoolMaxTotal());
        poolConfig.setMaxWaitMillis(redisConfig.getPoolMaxWait() * 1000);
        JedisPool jp = new JedisPool(poolConfig, redisConfig.getHost(), redisConfig.getPort(),
                redisConfig.getTimeout()*1000, redisConfig.getPassword(), 0);
        return jp;
    }
}

错误:ERR Client sent AUTH, but no password is set
客户端发送验证,但是redis服务器端没有设置密码
删除密码字段或设置redis服务器密码

5、RedisService封装对redis的操作

其中对象的存储使用fastjson序列化为json字符串

@Service
public class RedisService {

    @Autowired
    JedisPool jedisPool;
    /**
     * 获取当个对象
     * */
    public <T> T get(KeyPrefix prefix, String key,  Class<T> clazz) {
        Jedis jedis = null;
        try {
            jedis =  jedisPool.getResource();
            //生成真正的key
            //UserKey.getById,User.class 
            String realKey  = prefix.getPrefix() + key;
            String  str = jedis.get(realKey);
            T t =  stringToBean(str, clazz);
            return t;
        }finally {
            returnToPool(jedis);
        }
    }

    /**
     * 设置对象
     * */
    public <T> boolean set(KeyPrefix prefix, String key,  T value) {
        Jedis jedis = null;
        try {
            jedis =  jedisPool.getResource();
            String str = beanToString(value);
            if(str == null || str.length() <= 0) {
                return false;
            }
            //生成真正的key
            String realKey  = prefix.getPrefix() + key;
            int seconds =  prefix.expireSeconds();
            if(seconds <= 0) {
                jedis.set(realKey, str);
            }else {
                jedis.setex(realKey, seconds, str);
            }
            return true;
        }finally {
            returnToPool(jedis);
        }
    }

    /**
     * 判断key是否存在
     * */
    public <T> boolean exists(KeyPrefix prefix, String key) {
        Jedis jedis = null;
        try {
            jedis =  jedisPool.getResource();
            //生成真正的key
            String realKey  = prefix.getPrefix() + key;
            return  jedis.exists(realKey);
        }finally {
            returnToPool(jedis);
        }
    }

    /**
     * 增加值
     * */
    public <T> Long incr(KeyPrefix prefix, String key) {
        Jedis jedis = null;
        try {
            jedis =  jedisPool.getResource();
            //生成真正的key
            String realKey  = prefix.getPrefix() + key;
            return  jedis.incr(realKey);
        }finally {
            returnToPool(jedis);
        }
    }

    /**
     * 减少值
     * */
    public <T> Long decr(KeyPrefix prefix, String key) {
        Jedis jedis = null;
        try {
            jedis =  jedisPool.getResource();
            //生成真正的key
            String realKey  = prefix.getPrefix() + key;
            return  jedis.decr(realKey);
        }finally {
            returnToPool(jedis);
        }
    }

    private <T> String beanToString(T value) {
        if(value == null) {
            return null;
        }
        Class<?> clazz = value.getClass();
        if(clazz == int.class || clazz == Integer.class) {
            return ""+value;
        }else if(clazz == String.class) {
            return (String)value;
        }else if(clazz == long.class || clazz == Long.class) {
            return ""+value;
        }else {
            return JSON.toJSONString(value);
        }
    }

    @SuppressWarnings("unchecked")
    private <T> T stringToBean(String str, Class<T> clazz) {
        if(str == null || str.length() <= 0 || clazz == null) {
            return null;
        }
        if(clazz == int.class || clazz == Integer.class) {
            return (T)Integer.valueOf(str);
        }else if(clazz == String.class) {
            return (T)str;
        }else if(clazz == long.class || clazz == Long.class) {
            return  (T)Long.valueOf(str);
        }else {
            return JSON.toJavaObject(JSON.parseObject(str), clazz);
        }
    }

    private void returnToPool(Jedis jedis) {
        if(jedis != null) {
            jedis.close();
        }
    }

}
6、redis存储prefix设计

采用三层结构:
接口
抽象类

接口

public interface KeyPrefix {
    public int expireSeconds();//获取过期时间
    public String getPrefix();//获取封装后的key
}

抽象类

public abstract class BasePrefix implements KeyPrefix{

	
    private int expireSeconds;//过期时间单位秒
    private String prefix; //附加前缀

    public BasePrefix(String prefix) {//0代表永不过期
        this(0, prefix);
    }
    
    public BasePrefix( int expireSeconds, String prefix) {
        this.expireSeconds = expireSeconds;
        this.prefix = prefix;
    }
    public int expireSeconds() {
        return expireSeconds;
    }
    public String getPrefix() {
        String className = getClass().getSimpleName();
        return className+":" + prefix;
    }
}

实现类

public class UserKey extends BasePrefix{

	private UserKey(String prefix) {
		super(prefix);
	}

	public static UserKey getById = new UserKey("id");
	public static UserKey getByName = new UserKey("name");
}
7、测试
public class SampleController {
    @Autowired
    RedisService redisService;

     @RequestMapping("/redis/set")
    @ResponseBody
    public Result<Boolean> redisSet() {
        User user  = new User();
        user.setId(1);
        user.setName("1111");
        redisService.set(UserKey.getById, ""+1, user);//UserKey:id1
        return Result.success(true);
    }

    @RequestMapping("/redis/get")
    @ResponseBody
    public Result<User> redisGet() {
        User  user  = redisService.get(UserKey.getById, ""+1, User.class);
        return Result.success(user);
    }
}

获取的结果:
{“code”:0,“msg”:null,“data”:{“id”:1,“name”:“1111”}}

使用spring-boot-starter-data-redis

参考redis-10-spring-boot

  • jedis

jedis是redis的java客户端,通过它可以对redis进行操作。
与之功能相似的还包括:Lettuce等

  • spring-data-redis

spring-boot-data-redis 内部实现了对Lettuce和jedis两个客户端的封装,
默认使用的是Lettuce

1、添加依赖
 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
  </dependency>
2、外部配置文件
  • application.yaml
    spring:
      redis:
        host: 127.0.0.1
        port: 6379
        password: null
        pool:
          max-idle: 300
          min-idle: 10
          max-active: 600
          max-wait: 1000
        timeout: 0
3、配置类
@Configuration
public class RedisConfig {

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    /**
     * 实例化 RedisTemplate 对象
     * 
     */
    @Bean
    public RedisTemplate<String, Object> functionDomainRedisTemplate() {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        this.initRedisTemplate(redisTemplate, redisConnectionFactory);
        return redisTemplate;
    }

    /**
     * 序列化设置
     */
    private void initRedisTemplate(RedisTemplate<String, Object> redisTemplate, RedisConnectionFactory factory) {
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
        redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
        redisTemplate.setConnectionFactory(factory);
    }

    @Bean
    public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForHash();
    }

    @Bean
    public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForValue();
    }

    @Bean
    public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForList();
    }

    @Bean
    public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForSet();
    }

    @Bean
    public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForZSet();
    }
}
Spring Boot整合MyBatis-Plus和Redis可以通过以下步骤实现: 1. 添加依赖:在pom.xml文件中添加Spring Boot、MyBatis-Plus和Redis的依赖。 ```xml <!-- Spring Boot --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- MyBatis-Plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>${mybatis-plus.version}</version> </dependency> <!-- Redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 配置数据源:在application.properties或application.yml中配置数据库连接信息。 ```properties spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase spring.datasource.username=root spring.datasource.password=123456 ``` 3. 配置MyBatis-Plus:创建一个配置类,使用@MapperScan注解指定Mapper接口的扫描路径。 ```java @Configuration @MapperScan("com.example.mapper") public class MybatisPlusConfig { @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); } } ``` 4. 创建实体类和Mapper接口:创建实体类和对应的Mapper接口,使用注解进行映射。 ```java @Data @TableName("user") public class User { @TableId(type = IdType.AUTO) private Long id; private String name; } ``` ```java @Mapper public interface UserMapper extends BaseMapper<User> { } ``` 5. 添加Redis配置:在application.properties或application.yml中配置Redis连接信息。 ```properties spring.redis.host=localhost spring.redis.port=6379 ``` 6. 编写业务逻辑:创建Service类,注入Mapper和RedisTemplate,并编写业务逻辑。 ```java @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Autowired private RedisTemplate<String, Object> redisTemplate; @Override public User getUserById(Long id) { // 先从缓存中获取数据 String key = "user:" + id; User user = (User) redisTemplate.opsForValue().get(key); // 如果缓存中不存在,则从数据库中获取数据 if (user == null) { user = userMapper.selectById(id); // 将数据存入缓存 redisTemplate.opsForValue().set(key, user); } return user; } } ``` 这样,你就成功地将Spring Boot、MyBatis-Plus和Redis进行了整合。通过MyBatis-Plus进行数据库操作,并通过Redis进行缓存,提高系统性能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值