零基础spring boot第三天

简介

今天的主要任务是整合redis,所以需要我们提前在电脑下载好redis。(redis之前也有讲过,可作为数据库缓存,速度非常快)

步骤

这里我用的是Windows下的 redis 3.0,可以自行下载安装适合自己系统的redis
首先添加依赖

    <!-- redis -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
        <version>1.4.5.RELEASE</version>
    </dependency>

在 application-dev.properties 下添加如下配置

# Redis
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis连接端口
spring.redis.port=6379
# Redis连接密码(默认为空)
spring.redis.password=password
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=20
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1
# 连接池中的最大空闲连接、最小空闲连接
spring.redis.jedis.pool.max-idle=10
spring.redis.jedis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=1000

需要在com.example.backend_template.config下新建RedisConfigurer类

package com.example.backend_template.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * @ClassName RedisConfigurer Redis的配置类
 * @Description
 * @Author L
 * @Date Create by 2020/6/26
 */
@Configuration
@EnableCaching      //开启缓存
public class RedisConfigurer extends CachingConfigurerSupport {

    /**
     * redis 的各种配置信息,由框架注入
     */
    @Autowired
    private RedisProperties redisProperties;

    /**
     * 日志工具
     */
    private static final Logger log = LoggerFactory.getLogger(RedisConfigurer.class);

    @Bean
    public JedisConnectionFactory getConnectionFactory() {
        RedisStandaloneConfiguration redisStandaloneConfiguration =
                new RedisStandaloneConfiguration(redisProperties.getHost(), redisProperties.getPort());
        redisStandaloneConfiguration.setPassword(RedisPassword.of(redisProperties.getPassword()));
        JedisConnectionFactory factory = new JedisConnectionFactory(redisStandaloneConfiguration);
        log.info("The hostname of the redis connection is:{}, and the port is: {}", factory.getHostName(), factory.getPort());
        return factory;
    }

    public RedisTemplate<?, ?> getRedisTemplate() {
        RedisTemplate<?, ?> template = new StringRedisTemplate(getConnectionFactory());
        return template;
    }
}

在com.example.backend_template.service下新建RedisService类

package com.example.backend_template.service;

import java.util.List;

/**
 * @ClassName RedisService Redis常用方法
 * @Description 
 * @Author L
 * @Date Create by 2020/6/26
 */
public interface RedisService {

    /**
     * 设置给定 key 的值。如果 key 已经存储其他值, SET 就覆写旧值,且无视类型。
     * @param key
     * @param value
     * @return
     */
    boolean set(String key, String value);

    /**
     * 获取指定 key 的值。如果 key 不存在,返回 nil 。如果key 储存的值不是字符串类型,返回一个错误。
     * @param key
     * @return
     */
    String get(String key);

    /**
     * 设置 key 的过期时间。key 过期后将不再可用。
     * @param key
     * @param expire
     * @return
     */
    boolean expire(String key, long expire);

    /**
     * 存集合
     * @param key
     * @param list
     * @param <T>
     * @return
     */
    <T> boolean setList(String key, List<T> list);

    /**
     * 取集合
     * @param key
     * @param clz
     * @param <T>
     * @return
     */
    <T> List<T> getList(String key, Class<T> clz);

    /**
     * 将一个或多个值插入到列表头部。 如果 key 不存在,一个空列表会被创建并执行 LPUSH 操作。
     * 当 key 存在但不是列表类型时,返回一个错误。
     * @param key
     * @param obj
     * @return
     */
    long lpush(String key, Object obj);

    /**
     * 将一个或多个值插入到列表的尾部(最右边)。
     * 如果列表不存在,一个空列表会被创建并执行 RPUSH 操作。 当列表存在但不是列表类型时,返回一个错误。
     * @param key
     * @param obj
     * @return
     */
    long rpush(String key, Object obj);

    /**
     * 移除并返回列表的第一个元素。
     * @param key
     * @return
     */
    String lpop(String key);

    /**
     * 删除已存在的键。不存在的 key 会被忽略。
     * @param key
     * @return
     */
    long del(final String key);
}

在com.example.backend_template.service.impl下新建RedisServiceImpl类,这里需要alibaba的fastjson包,所示要提前有pom.xml添加如下依赖

        <!-- fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.41</version>
        </dependency>

package com.example.backend_template.service.impl;

import com.alibaba.fastjson.JSON;
import com.example.backend_template.service.RedisService;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Service;

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

/**
 * @ClassName RedisServiceImpl
 * @Description 
 * @Author L
 * @Date Create by 2020/6/26
 */
@Service
public class RedisServiceImpl implements RedisService {

    @Resource
    private RedisTemplate<String, ?> redisTemplate;


    @Override
    public boolean set(final String key, final String value) {
        boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
            @Override
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                connection.set(serializer.serialize(key), serializer.serialize(value));
                return true;
            }
        });
        return result;
    }

    @Override
    public String get(final String key){
        String result = redisTemplate.execute(new RedisCallback<String>() {
            @Override
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                byte[] value =  connection.get(serializer.serialize(key));
                return serializer.deserialize(value);
            }
        });
        return result;
    }

    @Override
    public long del(final String key){
        long result = redisTemplate.execute(new RedisCallback<Long>() {
            @Override
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                long value =  connection.del(serializer.serialize(key));
                return value;
            }
        });
        return result;
    }

    @Override
    public boolean expire(final String key, long expire) {
        return redisTemplate.expire(key, expire, TimeUnit.SECONDS);
    }

    @Override
    public <T> boolean setList(String key, List<T> list) {
        String value = JSON.toJSONString(list);
        return set(key,value);
    }

    @Override
    public <T> List<T> getList(String key,Class<T> clz) {
        String json = get(key);
        if(json!=null){
            List<T> list = JSON.parseArray(json, clz);
            return list;
        }
        return null;
    }

    @Override
    public long lpush(final String key, Object obj) {
        final String value = JSON.toJSONString(obj);
        long result = redisTemplate.execute(new RedisCallback<Long>() {
            @Override
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                long count = connection.lPush(serializer.serialize(key), serializer.serialize(value));
                return count;
            }
        });
        return result;
    }

    @Override
    public long rpush(final String key, Object obj) {
        final String value = JSON.toJSONString(obj);
        long result = redisTemplate.execute(new RedisCallback<Long>() {
            @Override
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                long count = connection.rPush(serializer.serialize(key), serializer.serialize(value));
                return count;
            }
        });
        return result;
    }

    @Override
    public String lpop(final String key) {
        String result = redisTemplate.execute(new RedisCallback<String>() {
            @Override
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                byte[] res =  connection.lPop(serializer.serialize(key));
                return serializer.deserialize(res);
            }
        });
        return result;
    }
}

测试

在com.example.backend_template.controller下新建RedisController类

package com.example.backend_template.controller;

import com.example.backend_template.service.RedisService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @ClassName RedisController
 * @Description 
 * @Author L
 * @Date Create by 2020/6/26
 */
@RestController
@RequestMapping("redis")
public class RedisController {

    @Resource
    private RedisService redisService;

    @PostMapping("/setRedis")
    public Boolean setRedis(String name) {
        return redisService.set("name", name);
    }

    @GetMapping("/getRedis")
    public String getRedis() {
        return redisService.get("name");
    }
}

启动项目,请求方式为POST,URL为 http://localhost:8080/redis/setRedis ,参数名为name,如下图方式进行访问
在这里插入图片描述
请求方式为GET,URL为 http://localhost:8080/redis/getRedis 如下图方式进行访问
在这里插入图片描述
如出现如上两种结果,则表示Redis已整合成功
原文链接:hello redis

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值