springboot 集成配置 redis 实现简单的业务逻辑

代码目录结构
springboot 集成配置 redis 实现简单的业务逻辑_第1张图片
注意:idea升级到2019以上版本(这里为了方便做单元测试)

① 添加依赖
<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-jupiter-api</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
        <!--springboot测试模板依赖-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
		<!--lombook依赖-->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<!--默认是lettuce客户端-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>
		<!--redis依赖commons-pool 这个依赖一定要加-->
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-pool2</artifactId>
		</dependency>
		<!--jackson中的objectMapper-->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>2.9.6</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-annotations</artifactId>
			<version>2.9.6</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.9.6</version>
		</dependency>
		<!--引入log4j2依赖-->
<!--		<dependency>-->
<!--			<groupId>org.springframework.boot</groupId>-->
<!--			<artifactId>spring-boot-starter-log4j2</artifactId>-->
<!--		</dependency>-->
	</dependencies>
② redis 配置类代码
@Configuration
public class RedisConfig extends CachingConfigurerSupport{



    /**
     * @description 缓存配置管理器
     * @author cx
     * @param factory
     * @return cacheManager
     */

    public CacheManager cacheManager(LettuceConnectionFactory factory)
    {
        /**以锁的方式创建RedisCacheWriter对象*/
        RedisCacheWriter writer = RedisCacheWriter.lockingRedisCacheWriter(factory);
        /**创建默认缓存配置对象*/
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        RedisCacheManager cacheManager = new RedisCacheManager(writer,config);
        return cacheManager;
    }
    /**
     * @description redis模板配置序列化
     *
     * @param factory
     * @return template
     */
    @Bean
    public RedisTemplate<String,Object> redisTemplate(LettuceConnectionFactory factory)
    {
        RedisTemplate<String,Object> template = new RedisTemplate<>();
        template.setConnectionFactory(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);

        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        /**key采用String的序列化方式*/
        /**在使用注解@Bean返回RedisTemplate的时候,同时也配置hashKey与hashValue的序列化方式*/
        template.setKeySerializer(stringRedisSerializer);
        /**value序列化方式采用jackson*/
        template.setValueSerializer(jackson2JsonRedisSerializer);
        /**hash的key也采用String的序列化方式*/
        template.setHashKeySerializer(stringRedisSerializer);
        /**hash的value序列化方式采用jackson*/
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

}
③application.yml 文件中配置服务器信息
server:
  port: 8081
spring:
  redis:
    port: 6379
    password: 123456 #这里填自己的tomcat密码
    host: 127.0.0.1 #服务搭建在本地
    lettuce:
      pool:
        max-active: 8 #最大活跃数
        max-idle: 8
        min-idle: 0
        max-wait: 1000
      shutdown-timeout: 100
  data:
    mongodb:
      database: 0
④ 实体层代码
/**
 * @author cx
 * @Time 2020/4/16 15:08
 * @Description
 */
public class Article implements Serializable {

    /**主键id*/
    private String id;
    /**文章标题*/
    private String title;
    /**正文内容*/
    private String content;
    /**作者*/
    private String author;
    /**创建日期*/
    private String createDate;
    /**点击量 or 阅读量*/
    private Long clickNum;

    public String getId() {
        return id;
    }

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getCreateDate() {
        return createDate;
    }

    public void setCreateDate(String createDate) {
        this.createDate = createDate;
    }

    public Long getClickNum() {
        return clickNum;
    }

    public void setClickNum(Long clickNum) {
        this.clickNum = clickNum;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("{");
        sb.append("\"id\":\"")
                .append(id).append('\"');
        sb.append(",\"title\":\"")
                .append(title).append('\"');
        sb.append(",\"content\":\"")
                .append(content).append('\"');
        sb.append(",\"author\":\"")
                .append(author).append('\"');
        sb.append(",\"createDate\":\"")
                .append(createDate).append('\"');
        sb.append(",\"clickNum\":")
                .append(clickNum);
        sb.append('}');
        return sb.toString();
    }
}
/**
 * @author cx
 * @Time 2020/4/13 21:18
 * @Description
 */
@Data
public class User implements Serializable{
    private String id;
    private String name;
    private Integer age;

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}
⑤ 业务层代码
/**
 * @author cx
 * @Time 2020/4/16 15:13
 * @Description
 */
@Service
@Log
public class ListCacheServiceImpl {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    public static Logger log = LoggerFactory.getLogger(ListCacheServiceImpl.class);

    @Resource(name = "redisTemplate")
    private ListOperations<String, Article> opsForList;

    /**
     * @description 实现首页文章信息的插入
     *
     * @param
     * @return
     */
    public void initArticle()
    {
        String key = "article:top5";
        /**设置当前时间*/
        LocalDateTime localDateTime = LocalDateTime.now();
        String dataTime = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        /**在mysql中查询5个文章*/
        log.info("模拟mysql查询 文章信息:");
        List<Article> list = new ArrayList<>();
        for (int i = 1; i < 6; i++)
        {
            Article ar = new Article();
            ar.setId("1000"+i);
            ar.setTitle("文章标题"+i);
            ar.setContent("文章内容数据"+i);
            ar.setClickNum((new Random().nextLong()+1));
            ar.setAuthor("小霞霞"+i);
            ar.setCreateDate(dataTime);
            list.add(ar);
        }
        log.info("-->存入Redis指定key中");
        opsForList.rightPushAll(key,list);
    }
    /**
     * @description 查询首页文章信息 (5条)
     *
     * @param
     * @return
     */
    public List<Article> selectArticleTop5()
    {
        String key = "article:top5";
        log.info("----->Redis中查询首页文章信息(5条)");
        return opsForList.range(key,0,4);
    }

    /**
     * @description 添加文章
     *
     * @param
     * @return
     */
    public long insertArticle(Article article)
    {
        log.info("插入数据存入redis");
        String key = "article:top5";
        return opsForList.leftPush(key,article);
    }

/**
 * @author cx
 * @Time 2020/4/19 16:46
 * @Description 订单队列
 */
@Service
public class ListQueueCacheServiceImpl {

    @Autowired
    private RedisTemplate redisTemplate;

    @Resource(name = "redisTemplate")
    private ListOperations<String, String> opsForList;

    public static Logger log = LoggerFactory.getLogger(ListCacheServiceImpl.class);

    /**
     * @description 1 送货描述实现
     *
     * @param
     * @return
     */
    public void orderQueue(String orderId)
    {
        String key = "queue:"+orderId;
        opsForList.leftPush(key,"1、商家发货");
        opsForList.leftPush(key,"2、快递小哥取货");
        opsForList.leftPush(key,"3、北京首都机场");
        opsForList.leftPush(key,"4、南京禄口机场");
        opsForList.leftPush(key,"5、建邺区住址");
        opsForList.leftPush(key,"6、收货");
    }

    /**
     * @description 2 快递小哥触发 队列事件
     *
     * @param
     * @return
     */
    public String orderTouch(String orderId){
        String keySucc = "queue:"+orderId+"success:";
        String key = "queue"+orderId;
        return opsForList.rightPopAndLeftPush(key,keySucc);
    }

    /**
     * @description 3 快递公司
     * 关注你这个快递还有几项任务完成
     * @param
     * @return
     */
    public List<String> orderSelect(String orderId)
    {
        /**待执行队列的key*/
        String key = "queue:"+orderId;
        return opsForList.range(key,0,-1);
    }

    /**
     * @description 4 用户
     *我的快递到哪了
     * @param
     * @return
     */
    public List<String> orderSelectSucc(String orderId)
    {
        String key = "queue:"+orderId+"succ";
        return opsForList.range(key,0,-1);
    }

}
/**
 * @author cx
 * @Time 2020/4/14 17:19
 * @Description redis 业务层
 */
@Service
public class UserServiceImpl {

    @Autowired
    private RedisTemplate redisTemplate;

    @Resource(name = "redisTemplate")
    private ValueOperations<String, String> string;

    @Resource(name = "redisTemplate")
    private HashOperations<String, String, User> hash;

    public static Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
    /**
     * @description
     *
     * @param key
     * @return string
     */
    public String getString(String key)
    {
        if (redisTemplate.hasKey(key))
        {
            log.info("----->Redis中查出来的!");
            //return (String) redisTemplate.opsForValue().get(key);
            /**修改优化redis模板*/
            return string.get(key);
        }else {
            String val = "redisTemplate模板学习lettuce客户端";
            log.info("----->MYSQL中查询出来的:"+val);
            //redisTemplate.opsForValue().set(key,val);
            /**修改优化redis模板*/
            string.set(key,val);
            log.info("----->在mysql中查出的消息存入redis中");
            return val;
        }
    }

    /**
     * @description 测试hash类型 演示
     *
     * @param id
     * @return User
     *
     * 根据ID查询用户对象信息
     * 先判断Redis中是否存在该key
     * 如果不存在,查询数据库MYSQL,并将结果添加到redis中。并返回
     * 如果存在,直接将结果在redis查询 并返回
     */
    public User selectById(String id)
    {
        if (hash.hasKey("user:13",id))
        {
            return hash.get("user:13",id);
        }else {
            log.info("----->查询mysql数据库");
            User u = new User();
            u.setId(id);
            u.setName("小霞霞");
            u.setAge(23);
            //redisTemplate.opsForHash().put("user:13",id,u);
            /**修改优化redis模板*/
            hash.put("user:13",id,u);
            return u;
        }
    }
}
⑥ 单元测试 测试代码
 * @author cx
 * @Time 2020/4/16 22:53
 * @Description
 */
@SpringBootTest
public class ListCacheTest {
    @Autowired
    private ListCacheServiceImpl listCacheService;

    @Test
    void t1()
    {
        /**初始化数据源*/
        List<Article> list = listCacheService.selectArticleTop5();
        for(Article a:list)
        {
            System.out.println(a.toString());
        }
    }

    @Test
    void t2()
    {
        Article article = new Article();
        article.setTitle("纽约新闻!");
        article.setAuthor("小霞霞");
        article.setId("10006");
        article.setCreateDate(null);
        article.setClickNum((long) 1000);
        listCacheService.insertArticle(article);
    }
}```

```java
/**
 * @author cx
 * @Time 2020/4/19 17:05
 * @Description
 */
@SpringBootTest
public class ListQueueCacheTest {
    @Autowired
    private ListQueueCacheServiceImpl listQueueCacheService;

    @Test
    void t1(){
        String orderId = "100001";
        listQueueCacheService.orderQueue(orderId);

        System.out.println("----->需要执行的物流任务列表--->执行");
        List<String> list = listQueueCacheService.orderSelect(orderId);

        for (String s:list)
        {
            System.out.println(s);
        }
    }
}
@SpringBootTest
class RedisdemoApplicationTests {

	@Autowired
	private UserServiceImpl userService;

	@Autowired
	private ListCacheServiceImpl listCacheService;

	@Test
	void contextLoads() {
		userService.getString("aaa");
	}

	@Test
	void t1()
	{
		String result = userService.getString("testRedis");
		System.out.println(result);
	}

	@Test
	void t2()
	{
		userService.selectById("1004");
	}

	@Test
	void t3()
	{
		listCacheService.initArticle();
	}
}

这边代码已经给的比较全了,可以试着去运行一下(记得装好redis)

你可能感兴趣的:(springboot,redis,redis,spring,boot)